主要用于创建对象。新添加类时,不会影响以前的系统代码。核心思想是用一个工厂来
根据输入的条件产生不同的类,然后根据不同类的 virtual函数得到不同的结果。 
   GOOD:适用于不同情况创建不同的类时 
BUG:客户端必须要知道基类和工厂类,耦合性差 。
 
  1. //基类  
  2. class COperation  
  3. {  
  4. public:  
  5.  int m_nFirst;  
  6.  int m_nSecond;  
  7.  virtual double GetResult() = 0;  
  8. };  

 

  1. //加法  
  2. class AddOperation : public COperation  
  3. {  
  4. public:  
  5.  virtual double GetResult()  
  6.  {  
  7.   return m_nFirst+m_nSecond;  
  8.  }  
  9. };  

 

  1. //减法  
  2. class SubOperation : public COperation  
  3. {  
  4. public:  
  5.  virtual double GetResult()  
  6.  {  
  7.   return m_nFirst-m_nSecond;  
  8.  }  
  9. };

 

  1. //工厂类  
  2. class CCalculatorFactory  
  3. {  
  4. public:  
  5.  static COperation* Create(char cOperator);  
  6. };  
  7.   
  8. COperation* CCalculatorFactory::Create(char cOperator)  
  9. {  
  10.  COperation *oper;  
  11.     //在 C#中可以用反射来取消判断时用的 switch,在C++中用什么呢?RTTI??  
  12.  switch (cOperator)  
  13.  {  
  14.  case '+':  
  15.   oper=new AddOperation();  
  16.   break;  
  17.  case '-':  
  18.   oper=new SubOperation();  
  19.   break;  
  20.  default:  
  21.   oper=new AddOperation();  
  22.   break;  
  23.  }  
  24.  return oper;  

 

  1. 客户端  
  2. int main()  
  3. {  
  4.  int a,b;  
  5.  cin>>a>>b;  
  6.   COperation * op=CCalculatorFactory::Create('-');  
  7.  op->m_nFirst=a;  
  8.  op->m_nSecond=b;  
  9.  cout<<op->GetResult()<<endl;  
  10.  return 0;  
  11. }