用简单工厂模式实现一个计算器类:
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class Operation 7 { 8 public: 9 Operation(double numA = 0, int numB = 0) : numberA(numA), numberB(numB) 10 { 11 } 12 virtual ~Operation() 13 { 14 cout << "~Operation()" << endl; 15 } 16 virtual double GetResult() 17 { 18 double result = 0; 19 return result; 20 } 21 protected: 22 double numberA; 23 double numberB; 24 }; 25 26 class OperationAdd : public Operation 27 { 28 public : 29 OperationAdd(double numA = 0, int numB = 0) : Operation(numA, numB) 30 { 31 } 32 virtual ~OperationAdd() 33 { 34 cout << "~OperationAdd()" << endl; 35 } 36 virtual double GetResult() 37 { 38 double result = 0; 39 result = numberA + numberB; 40 return result; 41 } 42 }; 43 class OperationSub : public Operation 44 { 45 public : 46 OperationSub(double numA = 0, int numB = 0) : Operation(numA, numB) 47 { 48 } 49 virtual ~OperationSub() 50 { 51 cout << "~OperationSub()" << endl; 52 } 53 virtual double GetResult() 54 { 55 double result = 0; 56 result = numberA - numberB; 57 return result; 58 } 59 }; 60 61 class OperationFactory 62 { 63 public : 64 virtual ~OperationFactory() 65 { 66 } 67 static Operation* createOperate(double numA, double numB, char operate) 68 { 69 Operation* oper; 70 switch (operate) 71 { 72 case ‘+‘ : 73 oper = new OperationAdd(numA, numB); 74 break; 75 case ‘-‘ : 76 oper = new OperationSub(numA, numB); 77 break; 78 default : 79 oper = 0; 80 break; 81 } 82 return oper; 83 } 84 }; 85 86 int main() 87 { 88 Operation* oper; 89 oper = OperationFactory::createOperate(2, 3, ‘+‘); 90 double result = oper->GetResult(); 91 cout << result << endl; 92 delete oper; 93 return 0; 94 }
简单工厂模式实现计算器
简单工厂模式的抽象实现:
1 #include <iostream> 2 3 using namespace std; 4 5 class Product 6 { 7 public : 8 Product() 9 { 10 } 11 ~Product() 12 { 13 } 14 virtual void CreateProduct() 15 { 16 } 17 private : 18 // 19 }; 20 21 class ProductA : public Product 22 { 23 public : 24 ProductA() : Product() 25 { 26 cout << "ProductA()" << endl; 27 } 28 ~ProductA() 29 { 30 cout << "~ProductA()" << endl; 31 } 32 virtual void CreateProduct() 33 { 34 } 35 }; 36 37 class ProductB : public Product 38 { 39 public : 40 ProductB() : Product() 41 { 42 cout << "ProductB()" << endl; 43 } 44 ~ProductB() 45 { 46 cout << "~ProductB()" << endl; 47 } 48 virtual void CreateProduct() 49 { 50 } 51 }; 52 53 class SimpleFactory 54 { 55 public : 56 static Product* Create(int type) 57 { 58 //Product *prod; 59 switch (type) 60 { 61 case 1: 62 prod = new ProductA; 63 break; 64 case 2: 65 prod = new ProductB; 66 break; 67 default : 68 prod = 0; 69 } 70 return prod; 71 } 72 ~SimpleFactory() 73 { 74 delete prod; 75 } 76 private : 77 static Product *prod; 78 }; 79 Product* SimpleFactory::prod = 0; 80 81 int main() 82 { 83 Product* prod; 84 prod = SimpleFactory::Create(1); 85 return 0; 86 }
简单工厂模式
时间: 2024-10-10 10:31:03