大话设计模式
工厂模式和策略模式相结合
#include <iostream>
#include <math.h>
enum type{cashnormal, cashrebate, cashreturn};
typedef type CashType;
// 收费抽象类
class CashSuper
{
public:
virtual double acceptCash(double money){};
};
// 正常收费子类
class CashNormal : public CashSuper
{
public:
inline double acceptCash(double money)
{
return money;
}
};
// 打折收费子类
class CashRebate : public CashSuper
{
public:
CashRebate() = default;
CashRebate(double moneyRebate);
inline double acceptCash(double money)
{
return moneyRebate_ * money;
}
private:
double moneyRebate_;
};
CashRebate::CashRebate(double moneyRebate):moneyRebate_(moneyRebate){}
// 返利收费子类
class CashReturn : public CashSuper
{
public:
CashReturn() = default;
CashReturn(double moneyCondition, double moneyReturn);
double acceptCash(double money);
private:
double moneyCondition_;
double moneyReturn_;
};
CashReturn::CashReturn(double moneyCondition, double moneyReturn):moneyCondition_(moneyCondition), moneyReturn_(moneyReturn){}
double CashReturn::acceptCash(double money)
{
double result = money;
if (money > moneyCondition_)
{
result = money - floor(money/moneyCondition_)*moneyReturn_;
}
return result;
}
class CashContext
{
public:
CashContext() = default;
CashContext(CashType cashtype);
inline double GetResult(double money){
return cashsuper_->acceptCash(money);
}
~CashContext(){
if (cashsuper_ != nullptr){
delete cashsuper_;
cashsuper_ = nullptr;
}
}
private:
CashSuper* cashsuper_;
};
CashContext::CashContext(CashType cashtype)
{
switch (cashtype)
{
case cashnormal:
cashsuper_ = new CashNormal();
break;
case cashrebate:
cashsuper_ = new CashRebate(0.8);
break;
case cashreturn:
cashsuper_ = new CashReturn(300, 100);
break;
default:
cashsuper_ = nullptr;
}
}
int main()
{
CashContext* cashcontext = new CashContext(cashreturn);
double totalprice = .0f;
double unitprice = .0f;
int num = 0;
std::cout << "请输入商品单价: " << std::endl;
std::cin >> unitprice;
std::cout << "请输入商品数量: " << std::endl;
std::cin >> num;
totalprice = unitprice * num;
totalprice = cashcontext->GetResult(totalprice);
std::cout << "最终应付价格: " << totalprice << std::endl;
delete cashcontext;
return 0;
}