Factory method pattern(air: different from the abstract one)

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.


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.


Figure 23-3. Generic structure of the Factory Method pattern.



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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章