工厂模式小记

工厂模式是23种设计模式中的一种

分类

  1. 简单工厂模式
  2. 工厂方法模式
  3. 抽象工厂模式

简单工厂模式

image


// 车辆工厂 负责所有车辆的进出
public class CarFactory {
    public static Car getCar(String carName) {
        if (carName.equals("五菱宏光")) {
            return new WuLing();
        } else if (carName.equals("特斯拉")) {
            return new TesLa();
        }
        return null;
    }
}

缺点:每新增一种车类型 就得修改原来的代码 出错概率提升 可能会影响以前的代码 造成比较严重的线上问题


工厂方法模式

image


// 消费者
public class Consumer {
    public static void main(String[] args) {
        Car car1 = new TesLaFactory().getCar();
        Car car2 = new WuLingFacory().getCar();
        car1.name();		// 特斯拉
        car2.name();		// 五菱宏光
    }
}

缺点:每新增一种车类型 不需要修改代码 但是需要新增一种车辆工厂 如果有一千种、一万种工厂 代码冗余量非常大 也不利于团队成员维护

posted @ 2021-11-22 21:43  晚秋时节  阅读(44)  评论(0)    收藏  举报