//用简单工厂模式实现商场收费策略
#include <iostream>
using namespace std;
//现金收费抽象类
//抽象产品:抽象产品角色是所创建的所有对象的父类,负责描述所有实例所共有的公共接口
class CashSuper
{
public:
virtual double acceptCash(double money)=0; //纯虚函数:在函数原型后加"=0"
};
//具体产品:具体产品角色(子类)是创建目标,所有创建的对象都充当这个角色的某个具体类的实例。
//正常收费子类
class CashNormal:public CashSuper
{
public:
virtual double acceptCash(double money)
{
return money;
}
};
//打折收费子类
class CashReBate:public CashSuper
{
private:
double moneyRebate=0;
public:
CashReBate(double rebate)
{
this->moneyRebate = rebate;
}
virtual double acceptCash(double money)
{
return money*moneyRebate;
}
};
//返利收费子类
class CashReturn:public CashSuper
{
private:
double moneyCondition=100;
double moneyReturn=50;
public:
CashReturn(double Condition,double Return)
{
this->moneyCondition = Condition;
this->moneyReturn = Return;
}
virtual double acceptCash(double money)
{
double result = money;
if(money >= moneyCondition)
{
result = money - moneyReturn;
}
return result;
}
};
//工厂:由一个工厂对象决定创建出哪一种产品类的实例,由switch()实现;
//现金收费工厂
class CashFactory
{
public:
static CashSuper* createCashAccept(char type)
{
CashSuper* cs;
switch (type)
{
case '0':
cs = new CashNormal();
break;
case '1':
cs = new CashReturn(100,50);
break;
case '2':
cs = new CashReBate(0.8);
break;
}
return cs;
}
};
int main()
{
CashSuper* cash;
CashFactory factory;
cash = factory.createCashAccept('2');
cout<<cash->acceptCash(300)<<endl;
system("pause");
return 0;
}
设计模式——简单工厂模式(C++)——商场收费
最新推荐文章于 2024-09-19 09:00:55 发布