策略模式定义了一系列算法,分别封装起来,让他们之间可以互相替换,且算法的变化不会影响到使用算法的客户。
一.需求分析
某商场营业,收银员根据客户所购买商品单价和数量向客户收费。近日某些商品做活动,有两种打折方式:
1.根据折扣打八折;
2.满减,满300减100。
二.模块设计
context类中可以传入具体的打折策略,并根据策略的不同得到不同的收费结果。
三.代码实现
1.策略类
#ifndef CASHSUPER_H
#define CASHSUPER_H
/*
* 收费基类
*/
class CashSuper
{
public:
//收费单价 数量
virtual double acceptCash(double price, int num);
};
#endif
#include "CashSuper.h"
double CashSuper::acceptCash(double price, int num)
{
return 0.0;
}
2.原价
#ifndef CASHNORMAL_H
#define CASHNORMAL_H
#include "CashSuper.h"
/*
* 原价
*/
class CashNormal :
public CashSuper
{
//收费单价 数量
double acceptCash(double price, int num)override;
};
#endif
#include "CashNormal.h"
double CashNormal::acceptCash(double price, int num)
{
return price * num;
}
3.打折
#ifndef CASHREBATE_H
#define CASHREBATE_H
#include "CashSuper.h"
/*
* 打七折
*/
class CashRebate :
public CashSuper
{
public:
CashRebate(double rebate);
double acceptCash(double price, int num);
private:
double m_rebate; //折扣率
};
#endif
#include "CashRebate.h"
CashRebate::CashRebate(double rebate)
{
m_rebate = rebate;
}
double CashRebate::acceptCash(double price, int num)
{
return price * num * m_rebate;
}
4.满减
#ifndef CASHRETURN_H
#define CASHRETURN_H
#include "CashSuper.h"
/*
* 返利
*/
class CashReturn :
public CashSuper
{
public:
CashReturn(double condition, double ret);
double acceptCash(double price, int num);
private:
double m_condition; //返利条件
double m_return; //返利值
};
#endif
#include "CashReturn.h"
CashReturn::CashReturn(double condition, double ret)
{
m_condition = condition;
m_return = ret;
}
double CashReturn::acceptCash(double price, int num)
{
double result = price * num;
if (m_condition > 0 && result >= m_condition)
{
result = result - (result / m_condition) * m_return;
}
return result;
}
5.context上下文
#ifndef CASHCONTEXT_H
#define CASHCONTEXT_H
/*
* 管理策略
*/
#include"CashSuper.h"
#include"CashNormal.h"
#include"CashRebate.h"
#include"CashReturn.h"
class CashContext
{
public:
CashContext(int cashType);
double getResult(double price, double num);
private:
CashSuper* m_cs;
};
#endif
#include "CashContext.h"
CashContext::CashContext(int cashType)
{
m_cs = nullptr;
switch (cashType)
{
case 1: //原价
m_cs = new CashNormal();
break;
case 2: //八折
m_cs = new CashRebate(0.8);
break;
case 3: //300返100
m_cs = new CashReturn(300, 100);
break;
default:
break;
}
}
double CashContext::getResult(double price, double num)
{
return m_cs->acceptCash(price,num);
}
5.主函数
#include <iostream>
#include"CashContext.h"
using namespace std;
int main()
{
cout << "请输入单价:" << endl;
double price = 0;
cin >> price;
cout << "请输入数量:" << endl;
int num;
cin >> num;
cout << "请输入收费模式:" << endl;
cout << "1.原价" << endl;
cout << "2.八折" << endl;
cout << "3.满300反100" << endl;
int select = 0;
cin >> select;
CashContext* context = new CashContext(select);
cout << "费用为:" << context->getResult(price, num);
return 0;
}