随笔- 79  文章- 1  评论- 1  阅读- 1672 

概述

工厂方法模式 (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   x-yun  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示