17.1.  Creational Patterns

[ fromfile: factory.xml id: factory ]

By using patterns to manage object creation, we gain flexibility that makes it possible to choose or change the kinds of objects created or used at runtime, and also to manage object deletion automatically, especially in large software systems. Managing the creation of objects is important for flexibility in program design, maintaining a separation between layers of code, and can also be used to manage their later destruction.

In C++, a factory is a program component, generally a class, that is responsible for creating objects. The idea of a factory is to separate object creation from object usage.

A factory class generally has a function that obtains dynamic memory for the new object and returns a base class pointer to that object. This approach allows new derived types to be introduced without necessitating changes to the code that uses the created object.

We will discuss several design patterns that use factories and show examples of these design patterns.

When the responsibility for heap object creation is delegated to a virtual function, we call this a Factory method.

By making the factory method pure virtual and writing concrete derived factory classes, this becomes an abstract factory.

By imposing creation rules that prevent direct instantiation of a class, we can force clients to use Factory methods to create all instances. When we combine creation rules with a Factory method that always returns the same singleton object, this is an example of the Singleton pattern.

Consider two ways of creating a Customer:

     Customer* c1 = new Customer(name);
     Customer* c2 = CustomerFactory::instance()->newCustomer(name)

In the first case, we are hard-coding the class name and calling a constructor directly. The object will be created in memory using the default heap storage. Hard-coded class names in client code can limit the reusability of the code.

In the second case, we create a Customer object indirectly using a Factory method called newCustomer(). In fact, newCustomer() is being called on a singleton CustomerFactory instance. CustomerFactory is a singleton because only one instance is available to us, via a static Factory method, instance().