设计模式2:策略模式工厂
减少算法类与使用算法类之间的耦合;简化了单元测试,因为每个算法都有自己的类,可以单独测试
Operation.h:
#pragma once #include<iostream> #include<string> using namespace std; class Operation { public: virtual double GetResult(){return 0}; public: double numA_; double numB_; }; class OperationAdd :public Operation { public: virtual double GetResult() { return numA_+numB_; } } class OperationSub: public Operation { public: virtual double GetResult() { return numA_ - numB_; } }; class OperationFactory //简单模式工厂 { public: Operation* CreateOperation(tstring oper) { Operation*op = NULL; if(wcscmp(oper.c_str(),L"+") == 0) op = new OperationAdd(); else op = new OperationSub(); return op; } }; class OperationFactoryS //策略模式工厂 { public: OperationFactionS(wstring oper) { if(wcscmp(oper.c_str(),L"+") == 0) op = new OperationAdd(); else op = new OperationSub(); } void SetNumA(double num){ op->numA_ = num; } void SetNumB(double num){ op->numB_ = num; } double GetResult() { return op->GetResult(); } private: Operation *op; }
main.cpp
#define _CRTDBG_MAP_ALLOC #include<stdlib.h> #include<crtdbg.h> #include"Operation.h" int main() { //需要知道所有方法类 OperationAdd opAdd; opAdd.numA_ = 20; opAdd.NumB_ = 30; cout << op->GetResult() << "\n"; //需要知道工厂类和所有方法类的基类,不需要知道具体的方法类 OperationFactory fac; Operation* op = fac.CreateOperation(L"+"); op->numA_ = 20; op->numB_ = 30; cout << "简单工厂:" << op->GetResult() << "\n"; //只需要知道工厂类 OperationFactoryS *opFacs = new OperationFactoryS(L"+"); opFacs->SetNumA(20); opFacs->SetNumB(30); cout << "策略模式工厂:" << opFacs->GetResult() << "\n"; delete op; _CrtDumpMemoryLeaks(); system("pause"); return 0; }