天天看点

State 状态模式 状态机

#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <string>
#include <iostream>
#include <boost/format.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace boost;

class Context;

class State
{
public:
	virtual void Operation(shared_ptr<Context>) = 0;
	virtual void ChangeState(shared_ptr<Context>,shared_ptr<State>) = 0;
	virtual void OperationAndChangeState(shared_ptr<Context>) = 0;
};

class Context : public enable_shared_from_this<Context>
{
public:
	Context(){}
	virtual ~Context(){}

	void setState(shared_ptr<State> state)
	{
		_m_ptrState = state;
	}
	shared_ptr<State> getState()
	{
		return _m_ptrState;
	}
	//某种状态对应的操作
	void Operation1()
	{
		std::cout << "Operation1 Finished." << std::endl;
	}

	void Operation2()
	{
		std::cout << "Operation2 Finished." << std::endl;
	}

	void Operation3()
	{
		std::cout << "Operation3 Finished." << std::endl;
	}

	void OperationState()
	{
		_m_ptrState->OperationAndChangeState(shared_from_this());
	}


protected:
	shared_ptr<State> _m_ptrState;
	friend class State;
};
class StateC : public State
{
public:
	virtual void Operation(shared_ptr<Context> context)
	{
		context->Operation3();
	}
	virtual void ChangeState(shared_ptr<Context> context,shared_ptr<State> state)
	{
		context->setState(state);
	}
	virtual void OperationAndChangeState(shared_ptr<Context> context)
	{
		context->Operation3();
		auto state = make_shared<StateC>();
		ChangeState(context,state);
	}
};

class StateB : public State
{
public:
	virtual void Operation(shared_ptr<Context> context)
	{
		context->Operation2();
	}
	virtual void ChangeState(shared_ptr<Context> context,shared_ptr<State> state)
	{
		context->setState(state);
	}
	virtual void OperationAndChangeState(shared_ptr<Context> context)
	{
		context->Operation2();
		auto state = make_shared<StateC>();
		ChangeState(context,state);
	}
};

//StateA
class StateA : public State
{
public:
	virtual void Operation(shared_ptr<Context> context)
	{
		context->Operation1();
	}
	virtual void ChangeState(shared_ptr<Context> context,shared_ptr<State> state)
	{
		context->setState(state);
	}
	virtual void OperationAndChangeState(shared_ptr<Context> context)
	{
		context->Operation1();
		auto state = make_shared<StateB>();
		ChangeState(context,state);
	}
};





void testStateMode()
{
	shared_ptr<Context> context = make_shared<Context>();
	auto stateA = make_shared<StateA>();
	auto stateB = make_shared<StateB>();
	auto stateC = make_shared<StateC>();
	context->setState(stateA);
	context->OperationState();
	context->OperationState();
	context->OperationState();
}
           

继续阅读