首页 > 代码库 > C++设计模式从0进击-1-简单(静态)工厂模式

C++设计模式从0进击-1-简单(静态)工厂模式

简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。

不修改代码的话,是无法扩展的。

 
#include <iostream>using namespace std;class COperation{public:	int m_nFirst;	int m_nSecond;	virtual double GetResult()	{		double dResult = 0;		return dResult;	}};//加法class AddOperation: public COperation{	virtual double GetResult()	{		return m_nFirst+ m_nSecond;	}};//减法class SubOperation: public COperation{public:	virtual double GetResult()	{		return m_nFirst - m_nSecond;	}};

//工厂类
class CCaculatorFactory{public:	static COperation * Create(char cOperator);};COperation * CCaculatorFactory::Create(char cOperator){	COperation * oper;	switch(cOperator)	{	case '+':		oper = new AddOperation();		break;	case '-':		oper = new SubOperation();		break;	default:		oper = new AddOperation();		break;	}	return oper;}

int _tmain(int argc, _TCHAR * argv []){         int a, b;         cin >> a >> b;         COperation * op = CCaculatorFactory::Create('-');         op->m_nFirst = a;         op->m_nSecond = b;         cout << op->GetResult() << endl;         return 0;}


 
 
 

C++设计模式从0进击-1-简单(静态)工厂模式