Factory method pattern is similar to Abstract factory, the major difference being that the former requires sub-classing to create the product objects where as the later does not require. There may be a problem scenario with Factory Method, as having a sub-class for each product may not be desirable. This may be over come by having a parameterized factory method class implementation.
// Product Family
class CAbstractProduct
{
public:
CAbstractProduct();
virtual ~CAbstractProduct();
virtual bool Init() = 0; //
};
// ‘Factory Method’
class CFactory
{
public:
virtual CAbstractProduct* Create() = 0;
};
////////////////////////////////////////////////////////////
template <class TheProduct>
class CTemplateFactory : public CFactory
{
public:
CAbstractProduct * Create();
};
template <class TheProduct>
CAbstractProduct * CTemplateCreator
::Create()
{
CAbstractProduct *pClass = new TheProduct;
pClass->Init(); // Initialization function
return pClass;
}
Here is an example for the above implementation:
class MyClass : public CAbstractClass
{
public:
MyClass();
virtual ~MyClass();
bool Init(); //optional
private:
int m_nSomeVal;
};
MyClass::MyClass()
{
m_nSomeVal = 0;
}
MyClass::~MyClass() { }
// Initialize the object
bool MyClass::Init()
{
m_nSomeVal = 20;
printf(”I m been intiallized to %d!\n”, m_nSomeVal);
return true;
}
int main(int argc, char* argv[])
{
CTemplateCreator myClassCteator;
CAbstractClass *pMyClass = myClassCteator.Create();
return 0;
}
CTemplateFactory
It is not necessary to always derive CTemplateFactory from an AbstractFactory, but doing so give you a freedom to extend the Factory chain later.

