大话设计模式策略模式c++实现

策略模式

其他二十三种设计模式

#include<iostream>

using namespace std;

//策略模式(Strategy):定义算法家族,分别封装起来,让算法之间可以相互替换,且不会影响到使用算法的Client客户
//抽象收费策略
class CashSuper {
    
    
public:
	virtual double acceptCash(double money) = 0;
};

//正常收费类
class CashNormal :public CashSuper {
    
    
public:
	virtual double acceptCash(double money) {
    
    
		return money;
	}
};

//打折收费类
class CashRebate :public CashSuper{
    
    
public:
	CashRebate(double _moneyRebate) {
    
    
		this->moneyRebate = _moneyRebate;
	}

	virtual double acceptCash(double money) {
    
    
		return money * moneyRebate;
	}
private:
	double moneyRebate = 1.0;
};

//返利收费类
class CashReturn :public CashSuper {
    
    
public:
	CashReturn(double _moneyCondition, double _moneyReturn) {
    
    
		this->moneyCondition = _moneyCondition;
		this->moneyReturn = _moneyReturn;
	}

	virtual double acceptCash(double money) {
    
    
		double result = money;
		if (money >= moneyCondition) {
    
    
			result = money - (int)(money / moneyCondition) * moneyReturn;
			return result;
		}
		return result;
	}

private:
	double moneyCondition = 0.0;
	double moneyReturn = 0.0;
};

class CashContext {
    
    
public:
	CashContext(CashSuper* _pCashSuper) {
    
    
		this->pCashSuper = _pCashSuper;
	}

	double ContextInterface(double _money) {
    
    
		return this->pCashSuper->acceptCash(_money);
	}

	~CashContext()
	{
    
    
		if (this->pCashSuper!=NULL)
		{
    
    
			delete this->pCashSuper;
		}
	}

public:
	CashSuper* pCashSuper = NULL;
};

void test1() {
    
    
	CashContext* context = NULL;
	context = new CashContext(new CashNormal());
	cout << context->ContextInterface(700) << endl;

	context = new CashContext(new CashRebate(0.8));
	cout << context->ContextInterface(700) << endl;

	context = new CashContext(new CashReturn(300,100));
	cout << context->ContextInterface(700) << endl;
}

int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114163281
今日推荐