策略模式
前序
请实现一个商场收银软件,包含正常收费,打折收费和返利收费三种具体策略
策略模式
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
实现方式(UML类图)
实现代码
#include <stdio.h>
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
{
protected:
double moneyRebate;
public:
CashRebate() : moneyRebate(1){}
CashRebate(double _moneyRebate) : moneyRebate(_moneyRebate){}
virtual double acceptCash(double money)
{
return money * moneyRebate;
}
};
class CashReturn : public CashSuper
{
protected:
double moneyCondition;
double moneyReturn;
public:
CashReturn() : moneyCondition(0),moneyReturn(0){}
CashReturn(double _moneyCondition,double _moneyReturn)
: moneyCondition(_moneyCondition),moneyReturn(_moneyReturn)
{}
virtual double acceptCash(double money)
{
double result = money;
if(money >= moneyCondition) result -= (int)(money / moneyCondition) * moneyReturn;
return result;
}
};
class CashContext
{
protected:
CashSuper* cs;
public:
CashContext() : cs(0){}
~CashContext()
{
if(cs) delete cs;
}
CashContext& operator=(CashSuper* csuper)
{
if(cs) delete cs;
cs = csuper;
return *this;
}
double GetResult(double money)
{
return cs->acceptCash(money);
}
};
int main()
{
double total = 0;
int Type;
while(1)
{
printf("请输入收费方式(0~2,-1退出):");
scanf("%d",&Type);
if(Type == -1) break;
CashContext cc;
switch(Type)
{
case 0:
cc = new CashNormal();
break;
case 1:
cc = new CashReturn(300,100);
break;
case 2:
cc = new CashRebate(0.8);
break;
default:
cc = new CashNormal();
break;
}
double Price,Num;
printf("请输入单价:");
scanf("%lf",&Price);
printf("请输入数量:");
scanf("%lf",&Num);
total += cc.GetResult(Price * Num);
}
printf("总价:%f\n",total);
return 0;
}
运行结果
所有文件打包下载
posted on 2011-05-04 15:10
lwch 阅读(1350)
评论(0) 编辑 收藏 引用 所属分类:
设计模式