简单工厂模式

  1. //运算操作基类   
  2. class COperation   
  3. {   
  4. public:   
  5.     int m_nFirst;   
  6.     int m_nSecond;   
  7.     virtual double GetResult() //返回操作结果   
  8.     {   
  9.         double dResult=0;   
  10.         return dResult;   
  11.     }   
  12. };   
  13. //加法   
  14. class AddOperation : public COperation   
  15. {   
  16. public:   
  17.     virtual double GetResult()   
  18.     {   
  19.         return m_nFirst+m_nSecond;   
  20.     }   
  21. };   
  22. //减法   
  23. class SubOperation : public COperation   
  24. {   
  25. public:   
  26.     virtual double GetResult()   
  27.     {   
  28.         return m_nFirst-m_nSecond;   
  29.     }   
  30. };   
  31.   
  32. //工厂类,为了方便我用的静态函数   
  33. class CCalculatorFactory   
  34. {   
  35. public:   
  36.     static COperation* Create(char cOperator);   
  37. };   
  38.   
  39. COperation* CCalculatorFactory::Create(char cOperator)   
  40. {   
  41.     COperation *oper;   
  42.     //在C#中可以用反射来取消判断时用的switch,在C++中用什么呢?我觉得是RTTI,后面可以讲到   
  43.     switch (cOperator)   
  44.     {   
  45.     case '+':   
  46.         oper=new AddOperation();   
  47.         break;   
  48.     case '-':   
  49.         oper=new SubOperation();   
  50.         break;   
  51.     default:   
  52.         oper=new AddOperation();   
  53.         break;   
  54.     }   
  55.     return oper;   
  56. }   
  57.   
  58. //客户端   
  59. int main()   
  60. {   
  61.     int a,b;   
  62.     cin>>a>>b;   
  63.     COperation * op=CCalculatorFactory::Create('-');   
  64.     op->m_nFirst=a;   
  65.     op->m_nSecond=b;   
  66.     cout<<op->GetResult()<<endl;   
  67.     return 0;   
  68. }  

UML图:

 

     简单工厂模式说简单点就是在一个工场类里面,根据输入的不同的条件产生同一类的不同对象,然后根据类的多态性使对象具有多样性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值