概述

工厂方法模式 (Factory Method Pattern) 又称工厂模式、虚拟构造器 (Virtual Constructor) 模式、多态工厂 (Polymorphic Factory) 模式。这个模式由一个抽象工厂类、一个抽象产品类以及这两个抽象类各自的多个具体子类组成。继承自不同抽象类的具体子类一一对应,具体工厂子类创建对应的具体产品子类。

优点:克服了简单工厂模式中工厂类违反了“开闭原则”的问题。扩展新的产品类时不需要修改已有代码,只需要创建对应的两个具体子类即可,可扩展性好。

缺点:添加新产品类时,需要成对添加新类,一定程度上增加了系统复杂性。多个抽象类的使用会增加理解难度。

interface Product {
  void use();
}

class ProductA implements Product {
  void use() {
    // body of method
  }
}

class ProductB implements Product {
  void use() {
    // body of method
  }
}

interface Factory {
  Product createProduct();
}

class FactoryA implements Factory {
  public Product createProduct() {
    return new ProductA();
  }
}

class FactoryB implements Factory {
  public Product createProduct() {
    return new ProductB();
  }
}

public class Test {
  public static void main(String[] args) {
    Product p;
    Factory f;
    f = new FactoryB();  // or get from some properties/xml file
    p = f.createProduct();
    p.use();
  }
}

图示
image

参考

[1] 刘伟,设计模式,2011.

 posted on 2023-06-13 11:21  x-yun  阅读(11)  评论(0)    收藏  举报