策略模式
其他二十三种设计模式
#include<iostream>
using namespace std;
class CashSuper {
public:
virtual double acceptCash(double money) = 0;
};
class CashNormal :public CashSuper {
public:
virtual double acceptCash(double money) {
return money;
}
};
class CashRebate :public CashSuper{
public:
CashRebate(double _moneyRebate) {
this->moneyRebate = _moneyRebate;
}
virtual double acceptCash(double money) {
return money * moneyRebate;
}
private:
double moneyRebate = 1.0;
};
class CashReturn :public CashSuper {
public:
CashReturn(double _moneyCondition, double _moneyReturn) {
this->moneyCondition = _moneyCondition;
this->moneyReturn = _moneyReturn;
}
virtual double acceptCash(double money) {
double result = money;
if (money >= moneyCondition) {
result = money - (int)(money / moneyCondition) * moneyReturn;
return result;
}
return result;
}
private:
double moneyCondition = 0.0;
double moneyReturn = 0.0;
};
class CashContext {
public:
CashContext(CashSuper* _pCashSuper) {
this->pCashSuper = _pCashSuper;
}
double ContextInterface(double _money) {
return this->pCashSuper->acceptCash(_money);
}
~CashContext()
{
if (this->pCashSuper!=NULL)
{
delete this->pCashSuper;
}
}
public:
CashSuper* pCashSuper = NULL;
};
void test1() {
CashContext* context = NULL;
context = new CashContext(new CashNormal());
cout << context->ContextInterface(700) << endl;
context = new CashContext(new CashRebate(0.8));
cout << context->ContextInterface(700) << endl;
context = new CashContext(new CashReturn(300,100));
cout << context->ContextInterface(700) << endl;
}
int main() {
test1();
return 0;
}