《大话设计模式》实现代码
//cash.h
#ifndef _CASH_H_
#define _CASH_H_
#include <string>
using namespace std;
class CashSuper
{
public:
CashSuper() {}
virtual ~CashSuper() {}
virtual double acceptCash(double money) {}
};
class CashNormal: public CashSuper
{
public:
double acceptCash(double money);
};
class CashReturn: public CashSuper
{
public:
CashReturn(double condition = 0.0, double re = 0.0):moneyCondition(condition), moneyReturn(re) {}
~CashReturn() {}
double acceptCash(double money);
private:
double moneyCondition;
double moneyReturn;
};
class CashRebate: public CashSuper
{
public:
CashRebate(double rate = 1.0): cashRate(rate) {}
~CashRebate() {}
double acceptCash(double money);
private:
double cashRate;
};
class CashContext
{
public:
CashContext(const string &type);
~CashContext();
double getResult(double money);
void setType(const string &type);
private:
void setCash(const string &type);
CashSuper *cs;
};
CashContext::CashContext(const string &type):cs(NULL)
{
this->setCash(type);
}
CashContext::~CashContext()
{
if(cs != NULL)
{
delete cs;
cs = NULL;
}
}
void CashContext::setType(const string &type)
{
this->setCash(type);
}
void CashContext::setCash(const string &type)
{
if(type.compare("Normal") == 0)
cs = new CashNormal();
else if(type.compare("Return") == 0)
cs = new CashReturn(300.0, 100.0);
else if(type.compare("Rebate") == 0)
cs = new CashRebate(0.8);
else
cs = NULL;
}
double CashContext::getResult(double money)
{
if(cs != NULL)
return cs->acceptCash(money);
return 0;
}
double CashNormal::acceptCash(double money)
{
return money;
}
double CashReturn::acceptCash(double money)
{
double result = money;
if(result >= this->moneyCondition && this->moneyCondition > 0)
result -= (double)((int) (result / this->moneyCondition)) * this->moneyReturn;
return result;
}
double CashRebate::acceptCash(double money)
{
return money * cashRate;
}
#endif
#include <iostream>
#include <cstdio>
#include <string>
#include "cash.h"
using namespace std;
int main()
{
string type1("Normal");
string type2("Return");
string type3("Rebate");
double price = 80;
int num = 10;
CashContext context(type1);
printf("The total money is: %.2lf\n", price * num);
printf("Noraml strategy: %.2lf\n", context.getResult(price * num));
context.setType(type2);
printf("Return strategy: %.2lf\n", context.getResult(price * num));
context.setType(type3);
printf("Rebate strategy: %.2lf\n", context.getResult(price * num));
return 0;
}