Navigation: Appendix B: Dolphin Pattern Book > Class Patterns >
Sometimes one wants to construct an instance of one of a suite of classes, deciding between the classes at the time of instantiation. In order to avoid duplicating the decision making everywhere an instance is created, we need a mechanism for creating instances of related classes without necessarily knowing which will be instantiated.
Create an Abstract Factory by implementing an Abstract Class that answer instances of concrete classes (usually subclasses). class of the resultant instance is unknown to the client of the Abstract Factory.
There are two types of Abstract Factory:
|1.||The simple Abstract Factory is an Abstract Class defining Factory Methods to answer instances of concrete subclasses. The choice of which subclass to instantiate is completely defined by which method is used, and is unknown to the client. (See Color in the Known Uses section below.)|
|2.||The second form of Abstract Factory is an Abstract Class defining a common protocol of Factory Methods. Concrete subclasses of the abstract factory implement this protocol to answer instances of the appropriate suite of classes.|
For example, concrete subclass FactoryA will always answer instances from the SuiteA classes, and concrete subclass FactoryB will always answer instances from the SuiteB classes. The choice of which subclass to instantiate is defined by the choice of factory, and is unknown to the client.
Here is an example of the more complex form of Abstract Factory. (For an example of the simple form, see Color in the Known Uses section below.)
Imagine a need to support two windowing environments, Microsoft Windows and the X Window System and to create GUI widgets appropriate to the specific environment in use.
Create an Abstract Factory class WindowFactory defining methods like #createButton. Add subclasses MSWindowFactory and XWindowFactory which implement #createButton to answer instances of MSButton or XButton respectively. A window painter can then be given an instance of MSWindowFactory or XWindowFactory. Sending it the #createButton message will result in an instance of MSButton or Xbutton. Assuming they respond to the same protocol, the client can remain ignorant of the class of the resultant button.
The Color class is a simple Abstract Factory. It defines class methods, some of which answer instances of IndexedColor, others answer instances of RGB. The choice between answering an IndexedColor or an RGB is made entirely by the Color class methods.
Color red "Display it"
Color red: 10 green: 20 blue: 30 "Displayit"