工厂模式小记
工厂模式是23种设计模式中的一种
分类
- 简单工厂模式
- 工厂方法模式
- 抽象工厂模式
简单工厂模式

// 车辆工厂 负责所有车辆的进出
public class CarFactory {
public static Car getCar(String carName) {
if (carName.equals("五菱宏光")) {
return new WuLing();
} else if (carName.equals("特斯拉")) {
return new TesLa();
}
return null;
}
}
缺点:每新增一种车类型 就得修改原来的代码 出错概率提升 可能会影响以前的代码 造成比较严重的线上问题
工厂方法模式

// 消费者
public class Consumer {
public static void main(String[] args) {
Car car1 = new TesLaFactory().getCar();
Car car2 = new WuLingFacory().getCar();
car1.name(); // 特斯拉
car2.name(); // 五菱宏光
}
}
缺点:每新增一种车类型 不需要修改代码 但是需要新增一种车辆工厂 如果有一千种、一万种工厂 代码冗余量非常大 也不利于团队成员维护
即使再小的帆也能远航

浙公网安备 33010602011771号