Factory
Ξ March 28th, 2010 | → 0 Comments |
∇ Programming | ∇ Abstract, Architecture, C++, Design, Factory, Method, Pattern |
The Abstract Factory is a very interesting design pattern that provides an encapsulation mechanism to the creation of families of objects. Combining this with the Factory Method it is possible build a factory that, after ‘generator method’ being registered, enables a simple mapping between a string object and an object.
The example shows an abstract Product which implements a given interface. There are two concrete products that derive from the base definition: a BigProduct and a SmallProduct. Then we have the Factory<T> that will be the production line for objects of type T. In the example, with T = Product, we have Factory<Product> that allows to call registration and creation methods, respectivelly:
template <class P>
void Factory<P>::registerProduct(const std::string& key, const Generator& generator)
template <class P>
P* Factory<P>::newProduct(const std::string& key)
The trick is that during registration you must provide the Generator function (also known as Factory Method) that will be used as building method by the factory. In this implementation, the Generator
is defined by the Factory itself but it could be defined anywhere as long as it returns a pointer to an abstract product. The implemented generation is based on default construction:
template <class P> template <class DP> // where P is Product and DP any kind of Derived Product
P* Factory<P>::generate()
{
return new DP();
}
In practice, using the factory is quite simple…
int main (void)
{
typedef Factory<Product> GenericFactory; // Simplifying the factory type…
GenericFactory factory;
// Register products and ‘generation’ methods…
factory.registerProduct(”BigProduct”, GenericFactory::generate<BigProduct>);
factory.registerProduct(”SmallProduct”, GenericFactory::generate<SmallProduct>);
// Calling for product creation
// NOTE: The use of auto pointer ensures that newly allocated object
// is automatically destroyed as the end of scope
std::auto_ptr<Product> bp(factory.newProduct(”BigProduct”));
std::auto_ptr<Product> sp(factory.newProduct(”SmallProduct”));
bp->doFeature();
sp->doFeature();
return 0;
}
There is one very interesting evolution of this design that I’ve done, to enable runtime class registration. I’ll post on that the next time.










