Boost logo

Boost :

From: Christophe Meessen (christophe_at_[hidden])
Date: 2002-11-19 13:04:29


Hello

I recently met the need for an Object Factory. I according to some
configuration information I would instantiate different type of objects
derived from a same base class.
So I wrote a small and light STL class that would do just what I
wanted.It might be that such functionality could be usefull for other
people. I don't know if there is a standrad submission procedure or if
this is the way to suggest an idea or a draft implementation.

Here is the general usage principle.

In one .cxx file you instantiate the baseFactory singleton object. It is
accessed through static member variables so does not need to be declared
as extern.

// Declare the factory
Factory<MyBaseType> baseTypeFactory;

// Declare an instantiable class as global variable
Factory<MyBaseType>::Class<MyDerivedClass1> derivedClass1(
"DerivedClassOne" );

// Declare another instantiable class as global variable
// In any .cxx file of the file one can declare a new dervied class
instantiable by the factory.
Factory<MyBaseType>::Class<MyDerivedClass2> derivedClass1(
"DerivedClassTwo" );

int main()
{
      ...
     // Building objects
     MyBaseType * obj =
 Factory<MyBaseType>::buildObject("DerivedClassTwo");
    ...
}
The default class key type is a string. But it may be changed into an
integer or anything else. The returned value is NULL if the key type
does not match any know class factory.
In the use case I had, the constructor needed an argument. So my version
adds an argument to the buildObject method that will be passed to the
constructor of the object called with new. To follow the STL standard
one should also be able to add a specific allocator type.

I am not a template expert. So the current implementation may not be the
one the might please everybody.

Would there be any interrest in such thing for boost ? If there are
better solution I would be happy to know about it.

-- 
cheers,
Ch. Meessen

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk