大话设计模式C++实现--策略模式

// designpatten2_cashsuper.cpp : 定义控制台应用程序的入口点。
//商城收银软件
//采用策略模式:strategy
//
#include "stdafx.h"
#include<string>
#include<iostream>
using  namespace std;

//抽象类作为公共基类
class CashSuper
{
public:
virtual double acceptCash(double money)
{
return -1;
}
};
  
//正常收费子类,公有继承CashSuper
class CashNormal :public CashSuper
{
public:
double acceptCash(double money) override
{
return money;
}


};

//打折收费子类,公有继承CashSuper
class CashRebate :public CashSuper
{
private:
double moneyRebate = 1;
public:
CashRebate(double moneyRebate)
{
this->moneyRebate = moneyRebate;

 
double acceptCash(double money) override
{
return money*moneyRebate;
}


};




//返现收费子类,公有继承CashSuper
class CashReturn :public CashSuper
{
private:
double moneyCondition=0;
double moneyReturn = 0;
public:
CashReturn(double moneyCondition,double moneyReturn)
{
this->moneyCondition = moneyCondition;
this->moneyReturn = moneyReturn;
}


double acceptCash(double money) override
{
double result = money;
if (money >= moneyCondition)
result = money - ((int)(money / moneyCondition))*moneyReturn;
return result;
}
};


//context类
class CashContext
{
CashSuper* cs;
public:
CashContext(string type)
{
if (type == "正常收费")
cs = new CashNormal();
else if (type == "满300减100")
cs = new CashReturn(300, 100);
else if (type == "打8折")
cs = new CashRebate(0.8);
else
{
std::cerr << "error \n";
exit(1);
}//异常退出程序
}


double GetResult(double money)
{
return cs->acceptCash(money);
}
};

//应该是界面按钮功能,此处用函数代替
double buttun_click(double txtPrice, int txtNum, string type)
{
CashContext csuper = CashContext(type);
double totalPrices = 0;
totalPrices = csuper.GetResult(txtPrice*txtNum);
return totalPrices;
}

int _tmain(int argc, _TCHAR* argv[])
{
double total = 0;
double total1 = 0;

double txtPrice=200;
int txtNum=5;
string type = "打8折";
string type1 = "满300减100";

total = buttun_click(txtPrice, txtNum, type);
total1 = buttun_click(txtPrice, txtNum, type1);

cout << "单价:" << txtPrice << "   数量;" << txtNum << "   type:" << type <<"  合计:"<<total<< endl;
cout << "单价:" << txtPrice << "   数量;" << txtNum << "   type1:" << type1 << "  合计:" << total1 << endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值