③ 设计模式的艺术-03.工厂方法(Factory Method)模式

 

 

public interface Car {
    void run();
}

 

public class Audi implements Car {

    @Override
    public void run() {
        System.out.println("奥迪再跑!");
    }

}

 

public class Byd implements Car {

    @Override
    public void run() {
        System.out.println("比亚迪再跑!");
    }

}

 

public interface CarFactory {
    Car createCar();
}

 

public class AudiFactory implements CarFactory {

    @Override
    public Car createCar() {
        return new Audi();
    }

}

 

public class BydFactory implements CarFactory {

    @Override
    public Car createCar() {
        return new Byd();
    }

}

调用

public class Client {
	public static void main(String[] args) {
		Car c1 = new AudiFactory().createCar();
		Car c2 = new BydFactory().createCar();
		
		c1.run();
		c2.run();
	}
}

 

新增

public class Benz implements Car {

    @Override
    public void run() {
        System.out.println("奔驰再跑!");
    }

}

 

public class BenzFactory implements CarFactory {

    @Override
    public Car createCar() {
        return new Benz();
    }

}

 

posted @ 2018-03-22 20:30  ~沐风  阅读(240)  评论(0编辑  收藏  举报