Factory Design

Hi All,

I am implementing an object factory and here is a kind of pseudo code/structure of what I have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**** Factory.h and Factory.cpp ****/
// Singleton class
class MyFactory
{
   // Also defines the Instance() method.

   BaseClass* create_Object(const std::string& objectID)
   {
      //Looks in creatorMap for objectID and then calls the
      //corresponding CreateCallBackFn.
   }

   bool registerObjectCreator(const std::string& objectID, CreateCallBackFn fn)
   {
      //Adds objectID, fn to creatorMap for after checking for exitance etc.
   } 
private:
   std::map<std::string, CreateCallBackFn> creatorMap;
};

/**** DerivedA.h and DerivedA.cpp ****/
BaseClass* DerivedA_CallBackFn (const std::string& objectID)
{
   return new DerivedA();
}

DerivedA::public BaseClass
{
   // All class members, constructors etc
};

/**** Main.cpp ****/
int main ()
{
     std::string objectID = getObjectIdfromCommandline();

/*** My QUESTION Relates to here ****/

     MyFactory::Instance().registerObjectCreator(objectIDA,DerivedA_CallBackFn);
    MyFactory::Instance().registerObjectCreator      (objectIDB,DerivedB_CallBackFn);


    BaseClass* theBase = MyFactory::Instance().create_Object(objectID );
}

/**** DerivedB.h and DerivedB.cpp ****/
BaseClass* DerivedB_CallBackFn (const std::string& objectID)
{
   return new DerivedB();
}

DerivedB::public BaseClass
{
   // All class members, constructors etc
};


This factory works OK and is doing what I wanted it to do.
My question about this design is that when I have to add a new object (say DerivedB), I do that by adding DerivedB.h and DerivedB.cpp which is OK as I am "ADDING" new files and not changing existing ones.

But i also have to register my Object Creator method in main.cpp. Marked as "My QUESTION Relates to here" in the code.

This to the reader of my code or to a tester will be a common piece of existing code that I am changing.

Is there anyway I can avoid this? How can I register the view creator say within my Derived*.h or Derived*.cpp file?

Thanks

Rian
Last edited on
You *might* be able to do it with calling a function by initializing a global value from its return value, but the problem is that you can't guarantee the order of initialization and so the creatorMap may not have been initialized yet (crashes).

What I would do is have your factories be instances of the factory class, and each instance can be made aware of separate groups of classes. Even if you do not need this functionality, it makes more sense from an OO perspective than having static (global) data.
Last edited on
Topic archived. No new replies allowed.