Field Notes: Using the Factory Method Pattern

In the classic implementation of the Abstract Factory, I had an abstract class define the methods to create a family of objects. I derived a class for each different family I could have. Each of the methods defined in the abstract class and then overridden in the derived classes were following the Factory Method pattern.

Sometimes it is useful to create a hierarchical class structure that is parallel to an existing class structure, with the new hierarchy containing some delegated responsibilities. In this case, it is important for each object in the original hierarchy to be able to instantiate the proper object in the parallel hierarchy. A Factory Method can be used for this purpose.

The Factory Method pattern is commonly used when defining frameworks. This is because frameworks exist at an abstract level. Usually, they do not know and should not be concerned about instantiating specific objects. They need to defer the decisions about specific objects to the users of the framework.

The Factory Method Pattern: Key Features

Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Defer instantiation to subclasses.
Problem A class needs to instantiate a derivation of another class, but doesn't know which one. Factory Method allows a derived class to make this decision.
Solution A derived class makes the decision on which class to instantiate and how to instantiate it.
Participants and Collaborators Product is the interface for the type of object that the Factory Method creates. Creator is the interface that defines the Factory Method.
Consequences Clients will need to subclass the Creator class to make a particular ConcreteProduct.
Implementation Use a method in the abstract class that is abstract (pure virtual in C++). The abstract class' code refers to this method when it needs to instantiate a contained object but does not know which particular object it needs.
GoF Reference Pages 107–116.

Figure 19-2. Standard, simplified view of the Factory Method pattern.



..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset