Monday, September 22, 2008

Factory Pattern (a.k.a. virtual constructor)

Factory Method helps to model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate. We call this a Factory Pattern since it is responsible for "Manufacturing" an Object. It helps instantiate the appropriate Subclass by creating the right Object from a group of related classes. The Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code.

The Factory Pattern is all about "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" Thus, as defined by Gamma et al, "The Factory Method lets a class defer instantiation to subclasses".

This pattern is used when a class (the Creator) does not know beforehand all the subclasses that it will create.

* Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.
* Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.

Example: (http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Virtual_Constructor)
class Employee
{
public:
virtual ~Employee () {} // Native support for polymorphic destruction.
virtual Employee * create () const = 0; // Virtual constructor (creation)
virtual Employee * clone () const = 0; // Virtual constructor (copying)
};
class Manager : public Employee // "is-a" relationship
{
public:
Manager (); // Default constructor
Manager (Manager const &); // Copy constructor
~Manager () {} // Destructor
Manager * create () const // Virtual constructor (creation)
{
return new Manager();
}
Manager * clone () const // Virtual constructor (copying)
{
return new Manager (*this);
}
};
class Programmer : public Employee { /* Very similar to the Manager class */ };
Employee * duplicate (Employee const & e)
{
return e.clone(); // Using virtual constructor idiom.
}

More effective c++ Item 25

Because the function creates new objects, it acts much like a constructor, but because it can create different types of objects, we call it a virtual constructor. A virtual constructor is a function that creates different types of objects depending on the input it is given. Virtual constructors are useful in many contexts, only one of which is reading object information from disk (or off a network connection or from a tape).

A particular kind of virtual constructor — the virtual copy constructor — is also widely useful. A virtual copy constructor returns a pointer to a new copy of the object invoking the function.

etc.).


References:

http://gsraj.tripod.com/design/creational/factory/factory.html
http://en.wikipedia.org/wiki/Factory_method_pattern

No comments: