工厂方法模式优点:完全实现了ocp原则,实现了可扩展。
工厂方法模式常用场景:
1、java的Collection的iterator()。
2、调用者只需要获得抽象工厂,具体工厂由生产者根据逻辑或当前系统的状态,自动判断。
工厂方法模式角色:
1、抽象工厂:所有工厂类的顶级接口
2、具体工厂:
3、抽象产品:所有产品的顶级接口
4、具体产品:
例子:
抽象工厂:
interface Factory { Product createProduct(); }
具体工厂A
public FactoryA implement Factory { public Product createProduct(){ return new ProductA(); } }
具体工厂B
public FactoryB implement Factory { public Product createProduct(){ return new ProductB(); } }
抽象产品
interface Product{ void say(); }
具体产品A
public ProductA implement Product { public void say(){ System.out.println("hello A"); } }
具体产品B
public ProductB implement Product { public void say(){ System.out.println("hello B"); } }
客户端
public static void main(String[] args) { Product A = new FactoryA().createProduct(); Product B = new FactoryB().createProduct(); A.say(); B.say(); }
输出语句:
hello A
hello B