类厂实现
#pragma once
#include <map>
#include <iostream>
using namespace std;
class CShape
{
public:
CShape(void){};
~CShape(void){};
public:
virtual void SayHello() = 0;
};
class CRectangle:public CShape
{
public:
virtual void SayHello()
{
cout << " hello CRectangle "<<endl;
}
};
class CCircle:public CShape
{
public:
virtual void SayHello()
{
cout << " hello CCircle "<<endl;
}
};
class CTriangle:public CShape
{
public:
virtual void SayHello()
{
cout << " hello CTriangle "<<endl;
}
};
//创建器接口
template<typename TBase>
class ICreator
{
public:
virtual TBase* Create() = 0;
};
//创建接口的实现
template<typename TBase,typename T>
class ICreatorImpl :public ICreator<TBase>
{
public:
virtual TBase* Create()
{
return new T();
}
};
//类工厂
template<typename T,typename ID>
class CFactory
{
typedef map<ID,ICreator<T>*> MAP_ID_CREATOR;
public:
T* Create(ID id)
{
MAP_ID_CREATOR::iterator it = m_mapID2Creator.find(id);
if (m_mapID2Creator.end() == it)
return 0;
ICreator<T>* pICreator = it->second;
return pICreator->Create();
}
public:
template<typename TImpl>
void Register(ID id)
{
ICreatorImpl<T,TImpl>* pICreator = new ICreatorImpl<T,TImpl>();
m_mapID2Creator[id] = pICreator;
}
void UnRegister(ID id)
{
MAP_ID_CREATOR::iterator it = m_mapID2Creator.find(id);
if (m_mapID2Creator.end() != it)
{
ICreatorImpl<T,TImpl>* pICreator = it->second;
delete pICreator;
m_mapID2Creator.erase(it);
}
}
private:
MAP_ID_CREATOR m_mapID2Creator;
};
调用:
#include "Shap.h"
int main()
{
CFactory<CShape,int> _factory;
_factory.Register<CRectangle>(1);
_factory.Register<CCircle>(2);
_factory.Register<CTriangle>(3);
CShape* pShap1 = _factory.Create(1);
pShap1->SayHello();
CShape* pShap2 = _factory.Create(2);
pShap2->SayHello();
CShape* pShap3 = _factory.Create(3);
pShap3->SayHello();
getchar();
return 1;
}