//个人觉得策略模式与工厂模式很像
#include <string>
#include <math.h>
#include <iostream>
#include <stdlib.h>
class CashSuper
{
public:
virtual double acceptCash(double money) = 0;
};
class CashNormal :public CashSuper
{
public:
double acceptCash(double money)
{
return money;
}
};
class CashReturn :public CashSuper
{
private:
double moneyCondition;
double moneyReturn;
public:
CashReturn(double moneyCondition, double moneyReturn)
{
this->moneyCondition = moneyCondition;
this->moneyReturn = moneyReturn;
}
double acceptCash(double money)
{
double result = money;
if (moneyCondition)
result = money - floor(money / moneyCondition)*moneyReturn;
return result;
}
};
class CashRebate :public CashSuper
{
private:
double moneyRebate;
public:
CashRebate(double moneyRebate)
{
this->moneyRebate = moneyRebate;
}
double acceptCash(double money)
{
return money*moneyRebate;
}
};
class CashContext
{
private:
CashSuper* cs;
public:
CashContext(int type) :cs(NULL)
{
switch (type)
{
case 1:
{
cs = new CashNormal();
break;
}
case 2:
{
cs = new CashReturn(300, 100);
break;
}
case 3:
cs = new CashRebate(0.8);
break;
default:;
}
}
~CashContext()
{
if (cs != NULL)
{
delete cs;
cs = NULL;
}
}
double GetResult(double money)
{
return cs->acceptCash(money);
}
};
int main()
{
double total = 0;
double totalPrice = 0;
CashContext* cc1 = NULL;
cc1 = new CashContext(1);
totalPrice = cc1->GetResult(300);
total += totalPrice;
std::cout << "Type:正常收费 totalPrices:" << totalPrice << " total:" << total << std::endl;
totalPrice = 0;
CashContext* cc2 = NULL;
cc2 = new CashContext(2);
totalPrice = cc1->GetResult(700);
total += totalPrice;
std::cout << "Type:满300返100 totalPrices:" << totalPrice << " total:" << total << std::endl;
totalPrice = 0;
CashContext* cc3 = NULL;
cc2 = new CashContext(3);
totalPrice = cc1->GetResult(300);
total += totalPrice;
std::cout << "Type:打八折 totalPrices:" << totalPrice << " total:" << total << std::endl;
totalPrice = 0;
if (cc1 != NULL)
{
delete cc1;
cc1 = NULL;
}
if (cc2 != NULL)
{
delete cc2;
cc2 = NULL;
}
if (cc3 != NULL)
{
delete cc3;
cc3 = NULL;
}
return 0;
}