The abstract factory pattern

The intent of this pattern is to provide an interface for creating families of related or dependent objects without specifying their concrete classes [GHJ95].

To better understand how this pattern works, let us consider the following example. Suppose that the heart of a crop simulation system is an object provided with supervising behavior that controls the objects that need to be created during the simulation process. We will refer to this object as Simulator. Suppose that any plant, be it perennial or annual, is represented by its LeafSystem and RootSystem; a plant is conceived as a composition of these composing parts. It will be highly desirable to develop a simulation system that is built in a very generic way and capable to simulate different types of plants: Perennials or annuals. Such a system will be independent of the specific plant that is simulating. Therefore, Simulator will be asked to create instances (and their composing parts) of perennial or annual plants. How can we develop a generic simulation system that handles any type of plants? The abstract factory pattern can be used to solve this type of issues. The class diagram for the abstract factory pattern is shown in Figure 7-6.

AbstractPlantFactory is an abstract class that provides the most common behavior needed for simulating perennial and annual plants. The behavior needed to simulate a specific plant will be provided by a specific "factory," that is, subclass of AbstractPlantFactory. PerennialFactory is used to create composing parts of a perennial plant and AnnualFactory is used to create the composing parts of an annual plant. AbstractPlantFactory is provided with a method referred to as getFactory that will deliver the required factory. Once Simulator knows the kind of plant it needs to simulate, it will use the getFactory method to obtain the right factory.

Figure 7-6. Class diagram of the abstract factory pattern.

Note that both factories are provided with behavior capable of creating instances of LeafSystem and Root System for both types of plants. The use of the abstract factory pattern makes it easy to add new types of factories for creating new types of objects by only adding a few lines of code in a well-defined place. It is important to note that the user of the abstract factory, Simulator in this case, it completely independent of the factory system that creates objects.

0 0

Post a comment