• 设计模式——策略模式(C++实现)


    程序优化是用于消除程序中大量的if else这种判断语句

     1 #include <iostream>
     2 #include <string>
     3 
     4 using namespace std;
     5 
     6 class CashSuper
     7 {
     8 public:
     9         virtual double GetTotalCash(double ddwMoney) = 0;
    10 };
    11 
    12 class CashNormal:public CashSuper
    13 {
    14 public:
    15         virtual double GetTotalCash(double ddwMoney)
    16         {
    17                 return ddwMoney;
    18         }
    19 };
    20 
    21 class CashRebate: public CashSuper
    22 {
    23 public:
    24         CashRebate(float dwRebate):m_Rebate(dwRebate)
    25         {
    26 
    27         }
    28 
    29         virtual double GetTotalCash(double ddwMoney)
    30         {
    31                 return m_Rebate * ddwMoney;
    32         }
    33 
    34 private:
    35         float m_Rebate;
    36 };
    37 
    38 class CashContext
    39 {
    40 public:
    41         CashContext()
    42         {
    43         }
    44 
    45         CashContext(CashSuper* pstTmpCashSuper)
    46         {
    47                 m_pstCashSuper = pstTmpCashSuper;
    48         }
    49 
    50         void SetCashStrategy(CashSuper* pstTmpCashSuper)
    51         {
    52                 m_pstCashSuper = pstTmpCashSuper;
    53         }
    54 
    55         double GetTotalCash(double ddwMoney)
    56         {
    57                 return m_pstCashSuper->GetTotalCash(ddwMoney);
    58         }
    59 
    60 private:
    61         CashSuper *m_pstCashSuper;
    62 };
    63 
    64 int main(void)
    65 {
    66         CashContext* stCashContext = new CashContext(new CashNormal());
    67 
    68         cout<<"应付价钱为: "<< stCashContext->GetTotalCash(100)<< endl;
    69 
    70         stCashContext = new CashContext(new CashRebate(0.8));
    71 
    72         cout<<"应付价钱为: "<< stCashContext->GetTotalCash(100)<< endl;
    73 
    74         return 0;
    75 }
    76 ///////
    77 [root]$ ./strategy       
    78 应付价钱为: 100
    79 应付价钱为: 80
  • 相关阅读:
    TestNG测试用例编写和执行
    Myeclipse+TestNG白盒测试环境搭建
    Jmeter创建一个简单的http接口用例
    python 格式化日期
    测试需求分析总结
    mac终端配色
    浅谈游戏中BUFF的设计要点
    图片头代码
    My.Ioc 代码示例——避免循环依赖
    My.Ioc 代码示例——谈一谈如何实现装饰器模式,兼谈如何扩展 My.Ioc
  • 原文地址:https://www.cnblogs.com/070412-zwc/p/6766946.html
Copyright © 2020-2023  润新知