Boost logo

Boost :

From: Marco Costalba (mcostalba_at_[hidden])
Date: 2007-09-19 02:05:03


On 9/19/07, Stephen Torri <storri_at_[hidden]> wrote:
>
> Why did you choose to use a multimap for the container in the factory?
>

To allow ctor argument overloading.

Factory<BaseClass>::register_class<DerivedClass*(int)>("Derived"); // ctor nr 1
Factory<BaseClass>::register_class<DerivedClass*(const
char*)>("Derived"); // ctor nr 2

Base* obj1 = Factory<BaseClass>::object("Derived", 7); // calls ctor nr 1
Base* obj2 = Factory<BaseClass>::object("Derived", "this calls ctor Nr 2");

So you have many instances of the key ( "Derived" in this case) in
your map, each one associated to different argument types or also
argument's number because you can add as example:

Factory<BaseClass>::register_class<DerivedClass*(int,
float)>("Derived"); // ctor nr 3

Base* obj3 = Factory<BaseClass>::object("Derived", 2, 3.14); // calls ctor nr 3

> Can you store any type in the factory? That is your example shows you
> storing ParentClass and the derived types plus OtherClass. Are both a
> base class? Or is it two separate instances of the Factory therefore two
> singleton factories available to produce objects?
>

Exactly, you have two singletons (of different types):

Factory<BaseClass>

and

Factory<OtherClass>

In general terms you have one singleton factory type for each object
hierarchy. In case you foreseen to create objects all belonging to the
same base type you can wrap the functions to avoid user to specify to
what singleton you refer:

bool myRegister(...) {
    return Factory<MyBaseClass>::register(...);
 }

MyBaseClass* myObject(...) {
    return Factory<MyBaseClass>::object(...);
 }

etc...

Marco


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