简单工厂组合策略模式_反射

#include 
#include 

using namespace std;

typedef void* (*CreateClass)(int,int);

#define DECLARE_CLASS(className)\
	static CKDynamicClass *className##dc;

#define IMPLEMENT_CLASS(c,className)\
	CKDynamicClass* className::className##dc=\
	new CKDynamicClass(c,className::CreateInstance);

class CClassFactory
{
private:
	map   m_mapMethod;
public:
	void* GetClassByType(char cType,int nFirst,int nSecond)
	{
		map::const_iterator iter;
		iter=m_mapMethod.find(cType);
		if(iter!=m_mapMethod.end())
			return iter->second(nFirst,nSecond);
		else
			return NULL;
	}

	void RegisterMethod(char cType,CreateClass method)
	{
		m_mapMethod.insert(pair(cType,method));
	}

	static CClassFactory& GetInstance()
	{
		static CClassFactory classFactory;
		return classFactory;
	}   
};

class CKDynamicClass
{
public:
	CKDynamicClass(char cType,CreateClass method)
	{
		CClassFactory::GetInstance().RegisterMethod(cType,method);
	}
};

class COperation
{
protected:
	int m_nFirst;
	int m_nSecond;
public:
	COperation(int nFirst,int nSecond)
		:m_nFirst(nFirst),m_nSecond(nSecond)
	{}

	virtual double GetResult()=0;
};

class CContext
{
private:
	COperation *m_classOper;
public:
	CContext(char cType,int nFirst,int nSecond)
	{
		m_classOper=(COperation*)CClassFactory::GetInstance().GetClassByType(cType,nFirst,nSecond);
	}

	double GetResult()
	{
		double dResult=0.0;
		if(m_classOper!=NULL)
			dResult=m_classOper->GetResult();
		return dResult;
	}
};

class CAddOperation:public COperation
{
private:
	DECLARE_CLASS(CAddOperation)
public:
	CAddOperation(int nFirst,int nSecond)
		:COperation(nFirst,nSecond)
	{}

	static void* CreateInstance(int nFirst,int nSecond)
	{
		return new CAddOperation(nFirst,nSecond);
	}

	virtual double GetResult()
	{
		return m_nFirst+m_nSecond;
	}
};

IMPLEMENT_CLASS('+',CAddOperation)

class CSubOperation:public COperation
{
private:
	DECLARE_CLASS(CSubOperation)
public:
	CSubOperation(int nFirst,int nSecond)
		:COperation(nFirst,nSecond)
	{}

	static void* CreateInstance(int nFirst,int nSecond)
	{
		return new CSubOperation(nFirst,nSecond);
	}

	virtual double GetResult()
	{
		return m_nFirst-m_nSecond;
	}
};

IMPLEMENT_CLASS('-',CSubOperation)

/********扩展***************/
class CMulOperation:public COperation
{
private:
	DECLARE_CLASS(CMulOperation)
public:
	CMulOperation(int nFirst,int nSecond)
		:COperation(nFirst,nSecond)
	{}

	static void* CreateInstance(int nFirst,int nSecond)
	{
		return new CMulOperation(nFirst,nSecond);
	}

	virtual double GetResult()
	{
		return m_nFirst*m_nSecond;
	}
};
IMPLEMENT_CLASS('*',CMulOperation)
/************************************/

int main(void)
{
	char c;
	cin>>c;
	CContext *pContext=new CContext(c,4,3);
	cout<GetResult()<

你可能感兴趣的:(C/C++)