C++实现设计模式之 —策略与简单工程结合

策略模式封装算法

  1 // cash.cpp : 定义控制台应用程序的入口点。
  2 //
  3 #include "stdafx.h"
  4 #include<iostream>
  5 #include<string.h>
  6 #include <math.h>
  7 using namespace std;
  8 class CashSuper
  9 {
 10 public:
 11  virtual double accpetCash(double money)= 0;
 12 };
 13 class CashNormal:public CashSuper
 14 {
 15 public:
 16  double accpetCash(double money) override
 17  {
 18   return money;
 19  }
 20 };
 21 class CashRebate:public CashSuper
 22 {
 23 public:
 24  CashRebate(double moneyRebate)
 25  {
 26   moneyRebate = moneyRebate;
 27  }
 28  double accpetCash(double money) override
 29  {
 30   return money * moneyRebate;
 31  }
 32 private:
 33  double moneyRebate;
 34 };
 35 class CashReturn:public CashSuper
 36 {
 37 public:
 38  CashReturn(double moneyCondition,double moneyReturn)
 39  {
 40   this->moneyCondition = moneyCondition;
 41   this->moneyReturn = moneyReturn;
 42  }
 43  double accpetCash(double money) override
 44  {
 45   double result = money;
 46   if(money > moneyCondition)
 47   {
 48    result = money - floor(money/moneyCondition)*moneyReturn;
 49    
 50   }
 51   return result;
 52  }
 53 private:
 54  double moneyCondition;
 55  double moneyReturn;
 56 };
 57 class CashFactory
 58 {
 59 public:
 60  static CashSuper *createCashAccpet(char type)
 61  {
 62   CashSuper *cs;
 63   switch(type)
 64   {
 65   case '1':
 66    cs = new CashNormal();
 67    break;
 68   case '2':
 69    cs = new CashReturn(300,100);
 70    break;
 71   case '3':
 72    cs = new CashRebate(0.8);
 73    break;
 74   }
 75   return cs;
 76  }
 77 };
 78 class CashContext
 79 {
 80 public:
 81  CashContext(char type)
 82  {
 83   switch(type)
 84   {
 85   case '1':
 86    cs = new CashNormal();
 87    break;
 88   case '2':
 89    cs = new CashReturn(300,100);
 90    break;
 91   case '3':
 92    cs = new CashRebate(0.8);
 93    break;
 94   }
 95  }
 96  CashSuper *cs;
 97  double GetResult(double money)
 98  {
 99   return cs->accpetCash(money);
100  }
101 };
102 
103 int _tmain(int argc, _TCHAR* argv[])
104 {
105  CashContext csuper('2');
106  double result = 0;
107  result = csuper.GetResult(500);
108  cout<<result<<endl;
109  system("pause");
110  return 0;
111 }
112  

 

posted @ 2018-07-04 13:54  wxmwanggood  阅读(173)  评论(0编辑  收藏  举报