bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

デザインパターン

デザインパターンのサイトを廻ってコードを書いた。

#include <iostream>

using namespace std;


//-------------------------------------
// 状態のインターフェイス
//-------------------------------------
class IState
{
public:
	virtual ~IState() { }

	virtual void method() = 0;
};


//-------------------------------------
// 状態A
//-------------------------------------
class StateA : public IState
{
public:
	void method()
	{
		cout << "StateA" << endl;
	}
};


//-------------------------------------
// 状態B
//-------------------------------------
class StateB : public IState
{
public:
	void method()
	{
		cout << "StateB" << endl;
	}
};


//-------------------------------------
// 状態を保持しているクラス
//-------------------------------------
class Context
{
private:
	IState* m_state;

public:
	Context() : m_state(0)
	{ }
	~Context()
	{
		if( NULL != m_state )
			delete m_state;
	}

	void method()
	{
		if( NULL == m_state )
			cout << "not set state" << endl;
		else
			m_state->method();
	}

	void changeState( IState* state )
	{
		if( m_state != NULL )
			delete m_state;

		m_state = state;
	}
};


int main()
{
	int input = 0;
	Context context;
	do
	{
		cout << "1: StateA, 2: StateB, 0: End" << endl;
		cin >> input;

		switch( input )
		{
		case 1:
			context.changeState( new StateA() );
			break;
		case 2:
			context.changeState( new StateB() );
			break;
		default:
			context.changeState( NULL );
			break;
		}
		context.method();
	}
	while( input != 0 );

	return 0;
}