简单工厂模式

【1】什么是简单工厂模式?

核心思想:创建一个具体工厂角色,根据客户端输入的条件产生相应的实体对象,然后由不同实体对象对virtual操作方法的调用得到不同的结果。

理解:根据条件生成不同的实例。利用多态的特性,调用同名方法,不同的实例将得到不同的结果。

【2】代码示例如下:

代码如下:

  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4 
  5 /*
  6 * 运算基类
  7 */
  8 class Operation
  9 {
 10 protected:
 11     double m_numberA;
 12     double m_numberB;
 13 
 14 public:
 15     double getNumberA()
 16     {
 17         return m_numberA;
 18     }
 19 
 20     void setNumberA(double dValue)
 21     {
 22         m_numberA = dValue;
 23     }
 24 
 25     double getNumberB()
 26     {
 27         return m_numberB;
 28     }
 29 
 30     void setNumberB(double dValue)
 31     {
 32         m_numberB = dValue;
 33     }
 34 
 35     virtual double getResult()
 36     {
 37         return 0;
 38     }
 39 };
 40 
 41 /*
 42 * 加法运算子类
 43 */
 44 class addOperation : public Operation
 45 {
 46 public:
 47     double getResult()
 48     {
 49         return m_numberA + m_numberB;
 50     }
 51 };
 52 
 53 /*
 54 * 减法运算子类
 55 */
 56 class subOperation : public Operation
 57 {
 58 public:
 59     double getResult()
 60     {
 61         return m_numberA - m_numberB;
 62     }
 63 };
 64 
 65 /*
 66 * 乘法运算子类
 67 */
 68 class mulOperation : public Operation
 69 {
 70 public:
 71     double getResult()
 72     {
 73         return m_numberA * m_numberB;
 74     }
 75 };
 76 
 77 /*
 78 * 除法运算子类
 79 */
 80 class divOperation : public Operation
 81 {
 82 public:
 83     double getResult()
 84     {
 85         if (0 == m_numberB)
 86         {
 87             return 0; // 无意义
 88         }
 89 
 90         return m_numberA / m_numberB;
 91     }
 92 };
 93 
 94 /*
 95 * 构建简单工厂
 96 */
 97 class operFactory
 98 {
 99 public:
100     static Operation *createOperation(char c)
101     {
102         switch (c)
103         {
104         case '+':
105             return (new addOperation);
106         case '-':
107             return (new subOperation);
108         case '*':
109             return (new mulOperation);
110         case '/':
111             return (new divOperation);
112         default:
113             return (new addOperation);
114         }
115     }
116 };
117 
118 /*
119 * 客户端应用示例
120 */
121 void main()
122 {
123     Operation* pOper = operFactory::createOperation('+');
124     pOper->setNumberA(9);
125     pOper->setNumberB(99);
126     cout << pOper->getResult() << endl;
127 
128     delete pOper;
129     pOper = NULL;
130 
131     system("pause");
132 }
133 
134 // run result:
135 /*
136 108
137 请按任意键继续. . .
138 */

 

 

Good Good Study, Day Day Up.

顺序 选择 循环 总结

posted @ 2014-08-26 21:48  kaizenly  阅读(476)  评论(0编辑  收藏  举报
打赏