Factory Class

Factory classes are used to make an instance of a descendent of an abstract class. This type of class is described in Chapter 3 (pp 107-116) of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (available in our library). In this document I will descibe one method of implementing a factory class and also introduce a method for selecting an operation when the exact number of operations may change over time. This method will allow you to hide the operations available from the application interface so the interface does not have to be recompiled.

In this diagram, the program has defined an abstract class Figure is an abstract factory class. It has two types of concrete factory classes LineFigure and TextFigure. The method CreateManipulator of each concrete factory class creates an appropriate type of manipulator (they are clone functions). Manipulators are instances of the abstract class Manipulator. The client is a program that uses Manipulators. It only needs to know of the existence of the class Manipulator and the class Figure. These classes are defined in a header of a DLL containing the code and class definitions for each of the actual clone functions and manipulators. Because the actual classes (the classes other than the abstract classes) are never visible directly the number and type of the actual classes can be altered without ever changing the client. This means if we want to add a RectangleManipulator, we would do all of the work in the DLL and the client would not be changed.

This leaves one problem. Normally the client would have menu entries from which the users select the type of object they want to create. Since the client doesn't know what Manipulator classes are available, it is imposible to create such a menu. To solve this problem, the DLL that implements the Manipulators will have a generic CreateManipulator that uses a list box in a dialog to present the current list of Manipulator types.

The actual implementation of the Factory is somewhat simpler than the diagram above from Gamma et al. Our abstract class Manipulator will have a CreateManipulator function that clones the type of Manipulator requested. The following diagram reflects the implementation we will use.

In the very simple example we will use, the client will display an incrementer similar to the push button device used by some museums to count visitors. This device will be a bit more complicated since we will allow the count to be in integers or letters. After building this interface, you will see the following dialog box when the program is actually counting.

Click here to download entire project.