本文共 1223 字,大约阅读时间需要 4 分钟。
产品类型接口:
public interface Car {}
产品工厂接口:
public interface ICarFactory { public Car createCar();}
产品一:
public class BMW implements Car { public BMW(){ System.out.println("create BMW."); }}
产品二:
public class Tesla implements Car { public Tesla() { System.out.println("Create Tesla."); }}
简单工厂:
public class CarFactory { public static Car createCar(String type) { switch (type) { case "BMW": return new BMW(); case "Tesla": return new Tesla(); default: return null; } }}
工厂方法一:
public class BMWFactory implements ICarFactory { @Override public Car createCar() { return new BMW(); }}
工厂方法二:
public class TeslaFactory implements ICarFactory { @Override public Car createCar() { return new Tesla(); }}
调用者:
public static void main(String[] args) { // 简单工厂 Car bmw = CarFactory.createCar("BMW"); Car tesla = CarFactory.createCar("Tesla"); // 工厂方法 ICarFactory bmwFactory = new BMWFactory(); ICarFactory teslaFactory = new TeslaFactory(); Car bmw2 = bmwFactory.createCar(); Car tesla2 = teslaFactory.createCar(); }}
转载地址:http://dhuta.baihongyu.com/