Create Mode -- Abstract Factory
程序员文章站
2022-06-15 09:47:59
...
1 抽象工厂模式
2 代码实现
interface Shape{
public void draw();
}
class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("draw rectangle");
}
}
class Square implements Shape{
@Override
public void draw() {
System.out.println("draw square");
}
}
interface Color{
public void fill();
}
class Green implements Color{
@Override
public void fill() {
System.out.println("fill green");
}
}
class Blue implements Color{
@Override
public void fill() {
System.out.println("fill blue");
}
}
abstract class AbstractFactory{
public abstract Shape productShape(String shape);
public abstract Color fillColor(String color);
}
class ShapeFactory extends AbstractFactory{
@Override
public Shape productShape(String shape) {
if (shape.isEmpty()){
return null;
}
if (shape.equals("rectangle")){
return new Rectangle();
}else if (shape.equals("square")){
return new Square();
}
return null;
}
@Override
public Color fillColor(String color) {
return null;
}
}
class ColorFactory extends AbstractFactory{
@Override
public Shape productShape(String shape) {
return null;
}
@Override
public Color fillColor(String color) {
if (color.isEmpty()){
return null;
}
if (color.equals("green")){
return new Green();
}else if (color.equals("blue")){
return new Blue();
}
return null;
}
}
class ProductFactory{
public static AbstractFactory getFactory(String factory){
if (factory.isEmpty()){
return null;
}
if (factory.equals("shape")){
return new ShapeFactory();
}else if (factory.equals("color")){
return new ColorFactory();
}
return null;
}
}
public class Test{
public static void main(String[] args){
AbstractFactory abstractFactory = ProductFactory.getFactory("shape");
abstractFactory.productShape("rectangle").draw();
}
}
推荐阅读
-
抽象工厂模式(Abstract Factory Pattern)
-
设计模式 | 抽象工厂模式(abstract factory)
-
Abstract Factory(抽象工厂模式)
-
Abstract Factory(抽象工厂模式)
-
java设计模式- abstract Factory (抽象工厂)模式
-
设计模式之抽象工厂模式(Abstract Factory)
-
设计模式-Abstract Factory
-
抽象工厂模式(Abstract Factory Pattern)
-
抽象工厂模式(Abstract Factory Pattern)
-
大白话抽象工厂模式(Abstract Factory Pattern)