C++设计模式从0进击-1-简单(静态)工厂模式

简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。

不修改代码的话,是无法扩展的。

 
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class COperation  
  5. {  
  6. public:  
  7.     int m_nFirst;  
  8.     int m_nSecond;  
  9.   
  10.     virtual double GetResult()  
  11.     {  
  12.         double dResult = 0;  
  13.         return dResult;  
  14.     }  
  15. };  
  16.   
  17. //加法  
  18. class AddOperation: public COperation  
  19. {  
  20.     virtual double GetResult()  
  21.     {  
  22.         return m_nFirst+ m_nSecond;  
  23.     }  
  24. };  
  25.   
  26. //减法  
  27. class SubOperation: public COperation  
  28. {  
  29. public:  
  30.     virtual double GetResult()  
  31.     {  
  32.         return m_nFirst - m_nSecond;  
  33.     }  
  34. };  

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //工厂类  
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. class CCaculatorFactory  
  2. {  
  3. public:  
  4.     static COperation * Create(char cOperator);  
  5. };  
  6.   
  7. COperation * CCaculatorFactory::Create(char cOperator)  
  8. {  
  9.     COperation * oper;  
  10.     switch(cOperator)  
  11.     {  
  12.     case '+':  
  13.         oper = new AddOperation();  
  14.         break;  
  15.     case '-':  
  16.         oper = new SubOperation();  
  17.         break;  
  18.     default:  
  19.         oper = new AddOperation();  
  20.         break;  
  21.     }  
  22.     return oper;  
  23. }  

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. int _tmain(int argc, _TCHAR * argv [])  
  2. {  
  3.          int a, b;  
  4.          cin >> a >> b;  
  5.          COperation * op = CCaculatorFactory::Create('-');  
  6.          op->m_nFirst = a;  
  7.          op->m_nSecond = b;  
  8.          cout << op->GetResult() << endl;  
  9.          return 0;  
  10. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值