Strategy パターン

Strategy パターン - Wikipedia

アルゴリズムを簡単に切り替えることができるようにしておくことで、同じ問題を別の方法で解くことを容易にする。Strategy パターンの クラス図は Bridge パターン - My Life as a Mock Quantのものと表面的には同じ。

#include<string>
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;

//strategy
class MaxSearchStrategy
{
public :
	virtual void Execute(const vector<int> & vec) = 0;
};
//concrete strategy 1
class STLStrategy : public MaxSearchStrategy
{
public :
	void Execute(const vector<int> & vec){
		vector<int>::const_iterator itr = max_element(vec.begin(),vec.end());
		cout << "===== STL Strategy =====\n";
		cout << "max: " << *itr << endl;
	}
};
//concrete strategy 2
class ForLoopStrategy : public MaxSearchStrategy
{
public :
	void Execute(const vector<int> & vec){
		int result = INT_MIN;
		for(unsigned int i = 0; i < vec.size(); i++){
			result = vec.at(i) >= result ? vec.at(i):result;
		}
		cout << "===== For Loop Strategy =====\n";
		cout << "max: " << result << endl;
	}
};
//context
class MaxSearcher
{
public :
	MaxSearcher(MaxSearchStrategy *strategy){
		this->strategy_ = strategy;
	}
	~MaxSearcher(){
		delete strategy_;
	}
	void Execute(const vector<int> & vec){
		strategy_->Execute(vec);
	}
private :
	MaxSearchStrategy *strategy_;
};
//main 
int main()
{
	//create sample data
	vector<int> data;
	data.push_back(2);
	data.push_back(5);
	data.push_back(4);
	data.push_back(1);
	data.push_back(6);
	data.push_back(3);
	//search max
	MaxSearcher *searcher1,*searcher2;
	searcher1 = new MaxSearcher(new STLStrategy());
	searcher1->Execute(data);
	searcher2 = new MaxSearcher(new ForLoopStrategy());
	searcher2->Execute(data);

	delete searcher1;
	delete searcher2;
	return 0;
}