#include "stdafx.h"
#include <iostream>
using namespace std;
/**
* 策略模式: 它定义了算法家族, 分别封装起来,让它们之间可以互相替换,
* 此模式让算法的变化,不会影响到使用算法的客户。
**/
class CashSuper
{
public:
virtual double acceptCash(double money){ return 0; }
};
// 正常收费
class CashNormal : public CashSuper
{
public:
virtual double acceptCash(double money) override
{
return money;
}
};
// 打折收费
class CashRebate : public CashSuper
{
private:
double _moneyReabate = 1;
public:
CashRebate(string moneyRebate)
{
_moneyReabate = atof(moneyRebate.c_str());
}
public:
virtual double acceptCash(double money) override
{
return money * _moneyReabate;
}
};
// 返利收费
class CashReturn : public CashSuper
{
private:
double _moneyCondition = 1.0;
double _moneyReturn = 1.0;
public:
CashReturn(string mCondition, string mReturn)
{
_moneyCondition = atof(mCondition.c_str());
_moneyReturn = atof(mReturn.c_str());
}
public:
virtual double acceptCash(double money) override
{
cout << "money=" << money << endl;
cout << "_moneyCondition=" << _moneyCondition << endl;
cout << "_moneyReturn=" << _moneyReturn << endl;
double result = money;
if ((money-_moneyCondition) >= 0.0001)
{
result = money - (int)((money / _moneyCondition))*_moneyReturn;
}
return result;
}
};
class CashContext
{
private:
CashSuper* cs;
double _rebate = 0.8;
double _moneyCondition = 300;
double _moneyReturn = 100;
private:
void CashContext_normal()
{
cs = new CashNormal();
}
void CashContext_Return(string Condition, string Return)
{
cs = new CashReturn(Condition, Return);
}
void CashContext_Rebate(string rebate)
{
cs = new CashRebate(rebate);
}
public:
// type = 'n', 其他参数无效
// type = 'r' parm1=满额, parm2=减额,
// type = 'z' parm1=折扣率,
CashContext(string type, string parm1 = "1", string parm2 = "0")
{
switch (type[0])
{
case 'n': // 正常收费
CashContext_normal();
break;
case 'r': // 满返
CashContext_Return(parm1, parm2);
break;
case 'z': // 打折扣
CashContext_Rebate(parm1);
break;
default:
cs = nullptr;
break;
}
}
void SetRebate(double rebate){ _rebate = rebate; }
void SetReturn(double mCondition, double mReturn)
{
_moneyCondition = mCondition;
_moneyReturn = mReturn;
}
public:
double GetResult(double money)
{
return cs->acceptCash(money);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CashContext *cc = new CashContext("r","300","50");
double totalPrices = 888;
double result = cc->GetResult(totalPrices);
cout << "总计:" << totalPrices << ", 打折后总计:" << result << endl;
totalPrices = result;
cc = new CashContext("z","0.1");
result = cc->GetResult(totalPrices);
cout << "总计:" << totalPrices << ", 打折后总计:" << result << endl;
return 0;
}
运行结果如下