设计模式(1):简单工厂模式
根据传入的参数的不同,自动生成需要的类的对象
简单工厂模式只是解决对象的创建问题
Operation.h:
1 #pragma once 2 3 #include<iostream> 4 #include<string> 5 6 using namespace std; 7 8 class Operation 9 { 10 public: 11 virtual double GetResult(){return 0}; 12 public: 13 double numA_; 14 double numB_; 15 }; 16 17 class OperationAdd :public Operation 18 { 19 public: 20 virtual double GetResult() 21 { 22 return numA_+numB_; 23 } 24 } 25 26 class OperationSub: public Operation 27 { 28 public: 29 virtual double GetResult() 30 { 31 return numA_ - numB_; 32 } 33 }; 34 35 class OperationFactory //工厂 36 { 37 public: 38 Operation* CreateOperation(tstring oper) 39 { 40 Operation*op = NULL; 41 if(wcscmp(oper.c_str(),L"+") == 0) 42 op = new OperationAdd(); 43 else 44 op = new OperationSub(); 45 return op; 46 } 47 };
main.cpp
#define _CRTDBG_MAP_ALLOC #include<stdlib.h> #include<crtdbg.h> #include"Operation.h" int main() { OperationFactory fac; Operation* op = fac.CreateOperation(L"+"); op->numA_ = 20; op->numB_ = 30; cout << op->GetResult() << "\n"; delete op; _CrtDumpMemoryLeaks(); system("pause"); return 0; }
输出结果50