C++ – Factory Method Implementation

c++design-patternsfactorytemplates

I have the following code for "factory" design pattern implementation.

class Pen{
public:
     virtual void Draw() = 0;
};

class RedPen : public Pen{
public:
     virtual void Draw(){
         cout << "Drawing with red pen" << endl;
     }
};

class BluePen : public Pen{
public:
     virtual void Draw(){
         cout << "Drawing with blue pen" << endl;
     }
};

auto_ptr<Pen> createPen(const std::string color){
     if(color == "red")
         return auto_ptr<Pen>(new RedPen);
     else if(color == "blue")
         return auto_ptr<Pen>(new BluePen);
}

But I heard that it can be done in a better way using "C++ templates". Can anyone help how it is done and how template approach is better than this?

Any thoughts

Best Answer

Another way is to dynamically register a creator function to a dynamical Factory object.

BluePen *create_BluePen() { return new BluePen; }
static bool BluePen_creator_registered = 
                       Factory::instance()->registerCreator("BluePen", 
                                                            create_BluePen);

One interesting effect in doing like this is that the static bool variable BluePen-creator-registered will be set prior main() starts thus making the registering automated.

These lines are sometimes made through ordinary macros, ie as

#define METAIMPL( _name ) \
_name *create_ ## _name() { return new _name; } \
static bool _name ## _creator_registered = \
                        Factory::instance()->registerCreator(# _name, \
                                                             create_ ## _name)

...and used close to the constructor

METAIMPL( BluePen ); // auto registers to the Factory

BluePen::BluePen() : Pen() {
   // something
}

Then the Factory's task will be to store and lookup these creator functions. I leave the rest as the exercise ;) ie the use of a METADECL macro

If you want more info, see here under chapter 4.1 Meta Information which also includes a method for expanding to include possibilities for inspector features

I learnt this from using ET++ that was a project to port old MacApp to C++ and X11. In the effort of it Eric Gamma etc started to think about Design Patterns

And...(May 7 2011) Finally came around to push an example to github
https://github.com/epatel/cpp-factory

Related Question