C++職責チェーンモデルの実現

1941 ワード

/*
	     :                ,             ,           ,  
	         ,          。
	
	               :
	(1)              ,                    。
	(2)             ,               。
	(3)             。

	    :
		        if..else    

	Created by Phoenix_FuliMa
*/

#include<iostream>
using namespace std;

class Handler
{
protected:
	Handler *_successor;

public:
	virtual void Handle(int value) = 0;
	void SetSuccessor(Handler *successor)
	{
		this->_successor = successor;
	}
};

class Handler_level_1: public Handler
{
public:
	virtual void Handle(int value)
	{
		if(value == 1)
		{
			cout<<"Handler_level_1 can handle"<<endl;
		}
		else
		{
			cout<<"Handler_level_1 can't handle"<<endl;
			this->_successor->Handle(value);
		}
	}
};

class Handler_level_2: public Handler
{
public:
	void Handle(int value)
	{
		if(value == 2)
		{
			cout<<"Handler_level_2 can handle"<<endl;
		}
		else
		{
			cout<<"Handler_level_2 can't handle"<<endl;
			_successor->Handle(value);
		}
	}
};

class Handler_level_end:public Handler
{
public:
	void Handle(int value)
	{
		if(value == 3)
		{
			cout<<"Handler_level_3 can handle"<<endl;
		}
		else
		{
			cout<<"No Handler can handle this value"<<endl;
		}
	}
};

int main()
{
	Handler_level_1 *handle_1 = new Handler_level_1();
	Handler_level_2 *handle_2 = new Handler_level_2();
	Handler_level_end * handle_end = new Handler_level_end();

	handle_1->SetSuccessor(handle_2);
	handle_2->SetSuccessor(handle_end);
	handle_end->SetSuccessor(NULL);

	handle_1->Handle(1);
	cout<<endl;
	handle_1->Handle(2);
	cout<<endl;
	handle_1->Handle(3);
	cout<<endl;
	handle_1->Handle(4);
	cout<<endl;
	
	delete handle_1;
	delete handle_2;
	delete handle_end;
	system("pause");
	return 0;
}