Factory
Defines an interface for creating objects. Allows subclasses to decide which concrete class to instantiate. The Factory is a Creator. It is usually abstract, although the create() method can provide a default implementation.
It is useful when
class Product { // ... }; class Factory { public: virtual Product * create( ) = 0; };
class Product_A : public Product { // ... }; class Factory_A : public Factory { public: virtual Product * create( ) { Product_A * p_product_a = new Product_A(); // ... return p_product_a; } }
Factory_A factory_a; Product * product = factory_a.create()
Prototype
Another example is the cloning factory, whose create() method make a copy of a prototype product. For example the concrete cloning factory could check that the prototype product is of the correct type and ask it to clone itself,
Product * create( Product * prototype ) { if ( Product_A * pa = dynamic_cast<Product_A *>( prototype ) ) return pa->Clone(); return NULL; }
The prototype does not need to be a Product, and the cloning can make use of an external helper (class or function).
Cloning is suitable when the instances of a class can have only a few different combinations of state. It allows to
The Factory is one of the patterns of the book of
Design Pattern, which also presents the related
Abstract Factory pattern.
The Factory pattern and its implementations are thoroughly discussed
in the book Modern C++ Desig by A. Alexandrescu.