欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Create Mode -- Abstract Factory

程序员文章站 2022-06-15 09:47:59
...

1 抽象工厂模式

Create Mode -- Abstract Factory

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();
    }
}