设计模式(五)之工厂方法模式

产品类型接口:

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();
    }
}
上一篇:设计模式(七)之观察者模式


下一篇:设计模式(八)之单例模式