首页 > 代码库 > 设计模式(1)--简单工厂模式
设计模式(1)--简单工厂模式
//ver1 class Operation { public: static double GetResult(double A, double B, char operate) { double result = 0; switch(operate) { case ‘+‘: result = A + B; break; case ‘-‘: result = A - B; break; default: break; } return result; } }; void main1() { double A = 1.1; double B = 2.2; char oper = ‘+‘; double result = Operation::GetResult(A, B, oper); }
//ver2 class Operation { public: Operation(){} ~Operation(){} protected: double _NumberA; double _NumberB; public: void SetNumberA(double A) { _NumberA = A; } double GetNumberA() { return _NumberA; } void SetNumberB(double B) { _NumberB = B; } double GetNumberB() { return _NumberB; } virtual double GetResult() { double result = 0; return result; } }; class OperationAdd : public Operation { public: virtual double GetResult() { double result = _NumberA + _NumberB; return result; } }; class OperationSub : public Operation { public: virtual double GetResult() { double result = _NumberA - _NumberB; return result; } }; //工厂 class OperationFactory { public: static Operation CreateOperate(char operate) { Operation *oper = NULL; switch(operate) { case ‘+‘: oper = new OperationAdd(); break; case ‘-‘: oper = new OperationSub(); break; default: break; } return *oper; } }; void main2() { Operation oper; oper = OperationFactory::CreateOperate(‘+‘); oper.SetNumberA(1.1); oper.SetNumberB(2.2); double result = oper.GetResult(); }
设计模式(1)--简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。