您的位置:首页 > 编程语言 > C语言/C++

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

2016-07-05 17:20 465 查看
// 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: