大话设计模式1 简单工厂模式 C++源码

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 class ComputeBase
  6 {
  7 public:
  8   //virtual 拼写出错
  9   //没写成纯虚函数,没有写实现,会出现链接错误
 10   virtual double operation(double pre, double next) = 0;
 11 };
 12 
 13 class Add: public ComputeBase
 14 {
 15 public:
 16   virtual double operation(double pre, double next);
 17 };
 18 
 19 double Add::operation(double pre, double next)
 20 {
 21   return pre+next;
 22 }
 23 
 24 class Sub: public ComputeBase
 25 {
 26 public:
 27   virtual double operation(double pre, double next);
 28 };
 29 
 30 double Sub::operation(double pre, double next)
 31 {
 32   return pre - next;
 33 }
 34 
 35 class Mul: public ComputeBase
 36 {
 37 public:
 38   virtual double operation(double pre, double next);
 39 };
 40 
 41 double Mul::operation(double pre, double next)
 42 {
 43   return pre * next;
 44 }
 45 
 46 class Div: public ComputeBase
 47 {
 48 public:
 49   virtual double operation(double pre, double next);
 50 };
 51 
 52 double Div::operation(double pre, double next)
 53 {
 54   if(next == 0)
 55     {
 56     cout << "除数不能为0" << endl;
 57     return 0;
 58     }  
 59 return pre / next;
 60 }
 61 class Simplefactory
 62 {
 63 private:
 64   ComputeBase * pBase;
 65 public:
 66   Simplefactory(unsigned char cInput);
 67   ~Simplefactory();
 68   double compute(double pre, double next);
 69 };
 70 
 71 Simplefactory::Simplefactory(unsigned char cInput)
 72 {
 73   switch(cInput)
 74   {
 75   case '+':
 76     pBase = new Add; break;
 77   case '-':
 78     pBase = new Sub; break;
 79   case '*':
 80     pBase = new Mul; break;
 81   case '/':
 82     pBase = new Div; break;
 83   default:
 84     cout << "undifined compution!" <<endl;
 85   }
 86 }
 87 
 88 Simplefactory::~Simplefactory()
 89 {
 90   if(pBase !=  NULL)
 91     delete pBase;
 92 }
 93 double Simplefactory::compute(double pre, double next)
 94 {
 95   return pBase->operation(pre, next);
 96 }
 97 
 98 int main()
 99 {
100   double pre, next;
101   char cCompute;
102   cout << "Please input two operators:" << endl;
103   cin >> pre >> next;
104   cout << "Please input the computor " << endl;
105   cin >> cCompute;
106   Simplefactory fact(cCompute);
107   cout << fact.compute(pre, next) << endl;
108   return 0;
109 }
posted @ 2012-04-30 15:38  Solon Tan  阅读(255)  评论(1编辑  收藏  举报