标签:style blog http color os io ar art div
【1】什么是工厂方法模式?
定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
【2】工厂方法模式代码示例
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Operation 6 { 7 public: 8 double numberA; 9 double numberB; 10 11 virtual double getResult() 12 { 13 return 0; 14 } 15 }; 16 17 class addOperation : public Operation 18 { 19 double getResult() 20 { 21 return numberA + numberB; 22 } 23 }; 24 25 26 class subOperation : public Operation 27 { 28 double getResult() 29 { 30 return numberA - numberB; 31 } 32 }; 33 34 class mulOperation : public Operation 35 { 36 double getResult() 37 { 38 return numberA * numberB; 39 } 40 }; 41 42 class divOperation : public Operation 43 { 44 double getResult() 45 { 46 return numberA / numberB; 47 } 48 }; 49 50 class IFactory 51 { 52 public: 53 virtual Operation *createOperation() = 0; 54 }; 55 56 class AddFactory : public IFactory 57 { 58 public: 59 static Operation *createOperation() 60 { 61 return new addOperation(); 62 } 63 }; 64 65 66 class SubFactory : public IFactory 67 { 68 public: 69 static Operation *createOperation() 70 { 71 return new subOperation(); 72 } 73 }; 74 75 class MulFactory : public IFactory 76 { 77 public: 78 static Operation *createOperation() 79 { 80 return new mulOperation(); 81 } 82 }; 83 84 class DivFactory : public IFactory 85 { 86 public: 87 static Operation *createOperation() 88 { 89 return new divOperation(); 90 } 91 }; 92 93 int main() 94 { 95 Operation *oper = MulFactory::createOperation(); 96 oper->numberA = 9; 97 oper->numberB = 99; 98 cout << oper->getResult() << endl; 99 return 0; 100 }
Good Good Study, Day Day Up.
顺序 选择 循环 总结
标签:style blog http color os io ar art div
原文地址:http://www.cnblogs.com/Braveliu/p/3942359.html