State 状态模式 状态机

本文通过C++代码示例展示了状态模式的实现方式,包括定义不同状态类及其操作,并演示了状态之间的转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值