[大话设计模式]商场促销-策略模式

//  大话设计模式-策略模式
//  采用商场促销
#include <iostream>

class cash_super
{
public:
	virtual double accept_cash(double money) = 0;
};
//正常收费
class cash_normal : public cash_super
{
public:
	virtual double accept_cash(double money){ return money;}
};
//打折
class cash_rebat : public cash_super
{
public:
	cash_rebat(double val):money_dec_rate(val){}
	virtual double accept_cash(double money){ return money * (1 - money_dec_rate);}
private:
	double money_dec_rate; // 打折率
};

//反现金
class cash_return : public cash_super
{
public:
	cash_return(double cash_condition_val, double cash_return_back_val):cash_condition(cash_condition_val), cash_return_back(cash_return_back_val){}
	virtual double accept_cash(double money)
	{
		double result = money;
		if (money >= cash_condition)
		{
			result =  money - static_cast<int>( money / cash_condition ) * cash_return_back ;
		}
		return result;
	}
private:
	double cash_condition;
	double cash_return_back;
};
class cash_content
{
public:
	cash_content(char type):p(0)
	{
		switch(type)
		{
		case 'a':
			p = new cash_normal();
			break;

		case 'b':
			p = new cash_rebat(0.9);
			break;

		case 'c':
			p = new cash_return(500, 200);
			break;

		default:
			std::cout << "error type" << std::endl;
			break;
		}
	}
	cash_super* get_cash_handle()const { return p;}
private:

	cash_super * p;
};
int main()
{
	cash_content *test = new cash_content('a');
	std::cout << "Money :" << test->get_cash_handle()->accept_cash(500) << std::endl;

	return 0;
}

这就是按照书上写的策略模式,感觉和简单工厂模式一模一样啊。


你可能感兴趣的:([大话设计模式]商场促销-策略模式)