工厂方法模式

2020-10-30  本文已影响0人  Exception_22bf
public void buildCar(Integer type) {
  if(type.intvalue() == 1) {
      // 创建奔驰
  }
  if(type.intvalue() == 2) {
      // 创建宝马
  }
  if(type.intvalue() == 3) {
      // 创建凯迪拉克
  }
......
}
// 先定义一个创建汽车接口
public interface BuildCar {
  // 创建车的抽象方法
  void build();
}
// 定义创建奔驰车的类
public class BcCar implements BuildCar {
      void build() {
        // 创建奔驰的具体逻辑
        ...
     }
}
// 定义创建宝马车的类
public class BmCar implements BuildCar {
      void build() {
        // 创建宝马的具体逻辑
        ...
     }
}
// 定义创建凯迪拉克车的类
public class KdlkCar implements BuildCar {
      void build() {
        // 创建凯迪拉克的具体逻辑
        ...
     }
}
// 创建工厂
public class CarFactory {
  public BuildCar getBuildCar(Integer type) {
       if(type.intvalue() == 1) {
          return new BcCar();
      }
      if(type.intvalue() == 2) {
          return new BmCar();
      }
      if(type.intvalue() == 3) {
          return new KdlkCar();
      }
    } 
}
CarFactory carFactory = new CarFactory ();
// 使用工厂类创建奔驰车
carFactory .getBuildCar(1).build();
后续同理
......
上一篇 下一篇

猜你喜欢

热点阅读