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
In the example you posted, neither a factory or a template approach makes sense to me. My solution involves a data member in the Pen class.
Of course, the color class would have to be adjusted to the drawing API you use — and perhaps be way more advanced than this one (different color spaces, etc).
Why not templates?
The reason it does not make sense to use templates, is that (presumably) the only difference between the different drawing operations is the color variable. So, by using templates (or manually declaring different classes, as you did), you will duplicate similar code. This will make your program large, and slow it down.
So, the draw function should either take the color as an argument, or (as in my example) have the color as a class data member.