mardi 14 avril 2020

What's the difference between Factory Method implementations?

GoF book states that there are two ways to implement Factory Method:

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)

In what cases should I use one approach instead of another. What the benefits and drawbacks when I prefer one approach instead of another?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire