大话设计模式之C++实现---简单工厂模式

呵呵,这段时间为了找工作,很多东西都没去学了!还是跟以前一样学完一样,再学另一样。每天进一小步,都有新的高度!

本程序是从大话设计模式里面所提出的,我用C++来实现(我总是没事就把C#改为C++,看来有时间也去学下。net的)

大话设计模式之C++实现---简单工厂模式_第1张图片

下面是 factory.h

#include <exception> #include <string> #include <iostream> using namespace std; #ifndef AFX_CLASS_OPERATION #define AFX_CLASS_OPERATION template <class T> class Operation { public: virtual T GetResult() { T result = 0; return result; } virtual Operation& operator =(const Operation &A) { return *this; } public: T _numberA; T _numberB; }; //加法 template <class T> class OperationAdd:public Operation<T> { public: virtual T GetResult() { T result = 0; result = _numberA + _numberB; return result; } }; //减法 template <class T> class OperationSub:public Operation<T> { public: virtual T GetResult() { T result = 0; result = _numberA - _numberB; return result; } }; //乘法 template <class T> class OperationMul:public Operation<T> { public: virtual T GetResult() { int result = 0; result = _numberA * _numberB; return result; } }; //除法 template <class T> class OperationDiv:public Operation<T> { public: virtual T GetResult() { T result = 0; if(_numberB == 0) { throw 1001; } result = _numberA / _numberB; return result; } }; #endif //类工厂 #ifndef AFX_CLASS_OPERATIONFACTORY #define AFX_CLASS_OPERATIONFACTORY template <class T> class OperationFactory { public: static Operation<T>* CreateOperate(string operate) { Operation<T> *oper=NULL; if(!operate.compare("+")) oper = new OperationAdd<T>; if(!operate.compare("-")) oper = new OperationSub<T>; if(!operate.compare("*")) oper = new OperationMul<T>; if(!operate.compare("/")) oper = new OperationDiv<T>; return oper; } }; #endif

 

接着是主程序:

#include "factory.h" #include <conio.h> int main(int argc,char *argv[]) { Operation<int> *oper = NULL; oper = OperationFactory<int>::CreateOperate("+"); oper->_numberA = 1; oper->_numberB = 2; cout<<oper->GetResult()<<endl; getch(); return 1; }

 

你可能感兴趣的:(大话设计模式之C++实现---简单工厂模式)