Dissecting Code

Monday, July 19, 2010

Factory Patterns

1. The Parameterized factory:

#include <iostream>

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

class Circle: public Shape
{
public:
void Draw(){ std::cout<<"Circle::Draw"; }
};

class Square: public Shape
{
public:
void Draw(){ std::cout<<"Sqaure::Draw"; }
};

enum ShapeType{ Shape_Circle, Shape_Square };

class Factory
{
public:
static Shape& CreateShape( ShapeType shapeType );
};

Shape& Factory::CreateShape( ShapeType type )
{
switch ( type )
{
case Shape_Circle: return *new Circle();
break;
case Shape_Square: return *new Square();
break;
default: break;
}
}

int main()
{
Shape& s=Factory::CreateShape( Shape_Circle );
s.Draw();
return 0;
}



Disadvantages: Adding a new type of shape will need changes in the Factory method.



Getting around by the use of templates, we have:



#include <iostream>

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

class Circle: public Shape
{
public:
void Draw(){ std::cout<<"Circle::Draw"; }
};

class Square: public Shape
{
public:
void Draw(){ std::cout<<"Sqaure::Draw"; }
};

template <class T>
class Factory
{
public:
static Shape& CreateShape();
};

template <class T>
/*static*/ Shape& Factory<T>::CreateShape()
{
return *new T();
}

int main()
{
Shape& s=Factory<Circle>::CreateShape();
s.Draw();
return 0;
}




There we have a much more concise version using the power of templates.

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home