工厂方法实现之间有什么区别?

What's the difference between Factory Method implementations?

GoF 书中指出有两种实现工厂方法的方法:

Consider the following issues when applying the Factory Method pattern:

  1. Two major varieties. The two main variations of the Factory Method pattern are the case when the Creator class is an abstract class and does not provide an implementation for the factory method it declares, and the case when the Creator is a concrete class and provides a default implementation for the factory method. It’s also possible to have an abstract class that defines a default implementation, but this is less common. The first case requires subclasses to define an implementation, because there’s no reasonable default. It gets around the dilemma of having to instantiate unforeseeable classes. In the second case, the concrete Creator uses the factory method primarily for flexibility. It’s following a rule that says, “Create objects in a separate operation so that subclasses can override the way they’re created.” This rule ensures that designers of subclasses can change the class of objects their parent class instantiates if necessary.
  2. Parameterized factory methods. Another variation on the pattern lets the factory method create multiple kinds of products. The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates will share the Product interface. In the Document example, Application might support different kinds of Documents. You pass CreateDocument an extra parameter to specify the kind of document to create.

Design Patterns (Design Patterns: Elements of Reusable Object-Oriented Software)

在什么情况下我应该使用一种方法而不是另一种方法。当我更喜欢一种方法而不是另一种方法时,有哪些优点和缺点?

提前致谢。

阅读本书的荣誉。大多数人尝试 #2 时认为 工厂方法模式,而实际上 #1 声称描述了两个 major 变体。

所以我们实际上处理的是引用文本中模式的三个略有不同的版本,尽管其中只有两个有编号。这些版本之间的差异取决于 Creator 对它想要的 Product 实现有多少信息。

  1. 具有抽象工厂方法的CreatorProduct实现一无所知,并将所有内容留给ConcreteCreator
  2. 具有默认值 工厂方法的Creator 大部分时间都知道它想要什么Product 实现,但并非总是如此;所以它允许 ConcreteCreator 覆盖默认值。
  3. 带有参数化工厂方法的Creator有一个Product实现菜单可供选择,并决定向ConcreteCreator 为.

因此在每个连续的版本中,Creator 逐渐获得更多关于 Product 实现的信息以及更多关于如何选择实现的逻辑。

在工厂方法模式中,Creator 将创建对象的责任委托给其子 classes,因为它“无法预料 class它必须创建的对象的数量。”(第 108 页)根据不同的品种,我们可以看到当 Creator 可以预期 一些 时模式如何略有变化有关要创建的 class 个对象的信息。

您选择的版本取决于您对编译时 Product 实现的了解程度。