DesignPatterns_State

/////////////////////////////////////////////////////////////////////////////////////
// State pattern
// - Allow an object to alter its behavior when its internal state changes. The object
//   will appear to change its class.
//
// Author     : ZAsia
// Date       : 15/05/17
// Warning    : In practice, declaration and implementation should
//              be separated(.h and .cpp).
///////////////////////////////////////////////////////////////////////////////////////
#include 
using namespace std;

// forward declaration
class Context;

// State
// - defines an interface for encapsulating the behavior associated with a particular
//   state of the Context.
// - each State oeration takes a Context instance as a parameter, letting State access
//   data from Context and change the connection's state.
class State
{
public:
	virtual void Handle(Context *context) = 0;
};

// ConcreteState subclasses
// - each subclass implements a behavior associated with a state of the Context.
class ConcreteStateA : public State
{
public:
	virtual void Handle(Context *context)
	{
		cout << "ConcreteStateA::Handle..." << endl;
	}
};

class ConcreteStateB : public State
{
public:
	virtual void Handle(Context *context)
	{
		cout << "ConcreteStateB::Handle..." << endl;
	}
};

// Context
// - defines the interface of interest of clients.
// - maintains an instance of a ConcreteState subclass that defines the current
//   state.
class Context
{
public:
	Context(State *state = nullptr) : _state(state) { }

	void Request()
	{
		if (_state)
		{
			_state->Handle(this);
		}
	}

	void ChangeState(State *state)
	{
		_state = state;
	}

private:
	State *_state;
};

// Collaborations
// - Context delegates state-specific requests to the current ConcreteState object.
// - A context may pass itself as an argument to the State object handling the 
//   request. This lets the State object access the context if neccessary.
// - Context is the primary interface for clients. Clients can configure a context with
//   State object. Once a context is configured, its clients don't have to deal with the
//   State object directly.
// - Either Context or the ConcreteState subclasses can decide which state succeeds
//   another and under what circumstances.
int main()
{
	State *pStateA = new ConcreteStateA();
	State *pStateB = new ConcreteStateB();
	Context *pContext = new Context(pStateA);

	pContext->Request();

	pContext->ChangeState(pStateB);
	pContext->Request();

	delete pContext;
	delete pStateB;
	delete pStateA;

	return 0;
}

///////////////////////////////////////////////////////////////
// 1.The State pattern puts all behavior associated with a particular state into
//   one object. Because all state-specific code lives in a State subclass, new
//   states and transitions can be added easily by defining new subclasses.
發佈了110 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章