标签:c++设计模式入门
简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。
不修改代码的话,是无法扩展的。
#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++设计模式入门
原文地址:http://blog.csdn.net/lightupheaven/article/details/38823067