工厂

/******************************************************************** 
 file name : Factory.h 
 author  :   Clark/陈泽丹 
 created :   2012-5-8
 JAVA的反射机制已经在此被实现了 。  
 虽然目前代码还较凌乱,达不到“神一般的操作”。 
 但麻雀虽小,五脏俱全,“双杀”到“暴走”还是有机会的。 
 实现反射还是有必要的,因为有时基指针的信息并不足以让你的程序做出优化算法,得转成子类指针,
 你才有足够的信息去做出准确高效的优化算法。 
 例如图形的检测碰撞。 不同的图形的碰撞检测有不同的高效算法, 如果全部都抽象到像素级的检测,则效率太低了。
 而此时,你只有基类指针, 你并不清楚这基类到底是从什么子类来的。
 所以需要反射!
 *********************************************************************/ 

#pragma 
#include <map>

using namespace std;

//映射工厂
template
<
	typename IdType,
	class FunClass
>
class Factory
{
public:
	bool Register(const IdType& _ID, FunClass* _pCreator)
	{
		if( 0 != _pCreator && m_FunMap.insert(IdToFunMap::value_type(_ID, _pCreator)).second)
		{
			return true;
		}
		return false;
	}

	bool Unregister(const IdType& _ID)
	{
		typename IdToFunMap::iterator it = m_FunMap.find(_ID);
		if (it != m_FunMap.end())
		{
			delete it;
			m_FunMap.erase(_ID);
			return true;
		}
		return false;
	}

protected:
	Factory(){}
	void DeleteItems()
	{
		typename IdToFunMap::iterator it = m_FunMap.begin();
		for(; m_FunMap.end() != it; it++)
		{
			delete it->second;
		}
		m_FunMap.clear();
	}
	typedef map<IdType, FunClass*> IdToFunMap;
	IdToFunMap m_FunMap;
};


//工厂错误处理-----------------------------------------------------------
template<typename IdType, typename ResultType>
class FactoryError
{
protected:
	ResultType OnUnknownType(const IdType& _ID)
	{
		cout<<"Unknow object type pass to factory!"<<endl;
		return 0;
	}
};


//建造者工厂-----------------------------------------------------------
template
<
	class ResultType,
	typename IdType,
	class FunClass,
	template<typename, class> class FactoryErrorPolicy = FactoryError
>
class CreaterFactory: public Factory<IdType, FunClass>, public FactoryErrorPolicy<IdType, ResultType>
{
public:
	~CreaterFactory(){ DeleteItems(); }
	virtual ResultType CreateObject(const IdType& _ID)
	{
		typename IdToFunMap::const_iterator it = m_FunMap.find(_ID);
		if( m_FunMap.end() != it)
		{
			return (*(it->second))();
		}
		return OnUnknownType(_ID);
	}
};



//反射工厂-----------------------------------------------------------   
class Reflex  
{  
private:  
	enum {REAL_CLASS_ID = 0};  
public:  
	virtual int GetRealClassID() = 0;  
};  
template<int v>  
class ReflexEx:public Reflex  
{  
protected:  
	ReflexEx(){}  
	virtual ~ReflexEx(){}  
public:  
	enum {REAL_CLASS_EX_ID = v};  
	virtual int GetRealClassID(){ return REAL_CLASS_EX_ID; }  
};  
//0不能用,因已做为基类ID了   
template<>  
class ReflexEx<0>{};  


你可能感兴趣的:(工厂)