23种设计模式之3.工厂模式

227 阅读2分钟

工厂模式是用来统一创建其他类的实例,使用者不需要关注对象是怎么创建的,只需要告诉工厂你需要创建什么,工厂就会返回给你对应的对象。实现责任划分与创建的细节屏蔽。

类图如下图所示:

classDiagram
Color <|-- Red
Color <|-- Blue
Color <|-- Yellow
Color: draw()
class Red{
draw()
}
class Blue{
draw()
}
class Yellow{
draw()
}
class ColorFactory{
getColor()
}

定义Color接口,以及颜色的具体实现类,具体实现类实现了Color接口。

public interface Color {
    void draw();
}
public class Blue implements Color {
    @Override
    public void draw() {
        System.out.println("this is blue");
    }
}
public class Red implements Color {
    @Override
    public void draw() {
        System.out.println("this is red");
    }
}
public class Yellow implements Color {
    @Override
    public void draw() {
        System.out.println("this is yellow");
    }
}

定义颜色制造工厂,通过颜色名创建对应的颜色对象。

public class ColorFactory {
    public static Color getColor(String colorString){
        switch (colorString){
            case "red":
                return new Red();
            case "blue":
                return new Blue();
            case "yellow":
                return new Yellow();
            default:
                return null;
        }
    }

    public static void main(String[] args) {
        Color red = ColorFactory.getColor("red");
        red.draw();
        Color blue = ColorFactory.getColor("blue");
        blue.draw();
        Color yellow = ColorFactory.getColor("yellow");
        yellow.draw();
    }
}

运行结果如下图所示:

image.png

工厂模式优点:

  1. 工厂中包含了判断逻辑,调用者需要创建对象的时候只需要知道名称就可以了。
  2. 可以通过引入配置文件,即可在不修改代码的情况下进行更换产品类,提高了系统的灵活性。
  3. 工厂类屏蔽了具体的对象创建,调用者不需要直接创建对象,实现了对责任的划分。

工厂模式缺点:

  1. 每增加一个产品就需要增加具体类和实现工厂,使得类的个数增加,在一定程度上增加了系统的复杂度。
  2. 工厂负责了所有的产品创建,工厂出现问题,则所有的产品的生产也会出现问题。
  3. 添加新产品,就需要在工厂中增加判断逻辑,破坏了“开闭原则”,产品类型增多时,工厂逻辑也会变得复杂,不利于维护。