Field Notes: Using the Factory Method Pattern
Abstract Factory can be implemented as a family of Factory Methods |
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 was following the Factory Method pattern.
Useful to bind parallel class hierarchies |
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. In the languages example mentioned previously, the Factory Method patterns bind the different collections with the different iterators associated with the collections, as shown in Figure 23-2.
Figure 23-2. Binding parallel class hierarchies.
Factory Method is used in frameworks |
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.