Pattern: Abstract Factory


Context

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.

Solution

Create an Abstract Factory class to answer instances of concrete classes (usually subclasses). The class of the resultant instance is unknown to the client of the Abstract Factory.

There are two types of Abstract Factory:

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.)

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.

Example

This is an example of the more complex form of Abstract Factory. (For an example of the simple form, see the Color in the Known Uses section below.)

Imagine supporting two windowing environments, Microsoft Windows™and the X Window System.

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.

Known Uses

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.

For example,

Color red
        an IndexedColor(16r100000D)

Color red: 10 green: 20 blue: 30
        a RGB(10,20,30)

Related Patterns