設計模式(六)策略模式Strategy

CalmReason發表於2016-03-31

意圖:定義一個系列演算法,把他們一個個封裝起來,並且使它們可互相替換。使得演算法可以獨立於使用它的客戶。

傳統C++方法實現:

#include <memory>
#include <iostream>
using namespace std;

class Strategy
{
public:
	virtual void doAlgorithm(void)=0;
	virtual ~Strategy(){}
protected:
};

class StrategyA : public Strategy
{
public:
	void doAlgorithm(void){cout<<"StrategyA::doAlgorithm()"<<endl;}
};

class StrategyB : public Strategy
{
public:
	void doAlgorithm(void){cout<<"StrategyB::doAlgorithm()"<<endl;}
};

class UseStrategy
{
public:
	UseStrategy(shared_ptr<Strategy> ps):ps_(ps){}
	void useAlgorithm(void)
	{
		shared_ptr<Strategy> ps = this->ps_.lock();
		ps->doAlgorithm();
	}
private:
	weak_ptr<Strategy> ps_;
};

int main(int, char *[])
{
	shared_ptr<Strategy> ps = make_shared<StrategyA>();
	UseStrategy user(ps);
	user.useAlgorithm();
	//新增了一個演算法
	ps = make_shared<StrategyB>();
	UseStrategy user1(ps);
	user1.useAlgorithm();
};

輸出:

StrategyA::doAlgorithm()
StrategyB::doAlgorithm()
請按任意鍵繼續. . .
現代C++實現,參考std::function




相關文章