设计模式(1)-状态模式(C++)

用C++语言重新编写状态模式,文章源出处<<设计模式之禅>>

// StateModel.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
class Context;
class LiftState;
class OpenningState;
class RunState;
class StopState;
class LiftState
{
public:	
	Context* context;
	void setContext(Context* _context){context = _context;}
	virtual void open() = 0;
	virtual void close()=0;
	virtual void run()=0;
	virtual void stop()=0;
};
class Context
{
public:
	LiftState* m_liftState;
	Context(){}
	LiftState* getLiftState(){return m_liftState;}
	void setLiftState(LiftState* liftState){m_liftState = liftState;m_liftState->setContext(this);}
	void open(){m_liftState->open();}
	void close(){m_liftState->close();}
	void run(){m_liftState->run();}
	void stop(){m_liftState->stop();}
	static LiftState* openningState;
	static LiftState* closeState;
	static LiftState*  runState;
	static LiftState* stopState;

};
class OpenningState:public LiftState
{
public:	
	void close()
	{
		context->setLiftState(Context::closeState);
		context->getLiftState()->close();
	}
	void open()
	{
		cout<<"电梯打开"<<endl;
	}
	void run()
	{
		//do nothing
	}
	void stop()
	{
		// do nothing
	}
};
class CloseState:public LiftState
{
	void close()
	{
		cout<<"电梯关闭了"<<endl;
	}
	void open()
	{
		context->setLiftState(Context::openningState);
		context->getLiftState()->open();
	}
	void run()
	{
		context->setLiftState(Context::runState);
		context->getLiftState()->run();
	}
	void stop()
	{
		context->setLiftState(Context::stopState);
		context->getLiftState()->stop();
	}
};
class RunState:public LiftState
{
public:
	void close()
	{
		//do nothing
	}
	void open()
	{
		//do nothing
	}
	void run()
	{
		cout<<"电梯运行中"<<endl;
	}
	void stop()
	{
		context->setLiftState(Context::stopState);
		context->getLiftState()->stop();
	}
};
class StopState:public LiftState
{
	void close()
	{
		//do nothing
	}
	void open()
	{
		context->setLiftState(Context::openningState);
		context->getLiftState()->open();
	}
	void run()
	{
		context->setLiftState(Context::runState);
		context->getLiftState()->run();
	}
	void stop()
	{
		cout<<"电梯停止了"<<endl;
	}
};




LiftState* Context::openningState = new OpenningState();
LiftState* Context::closeState = new CloseState();
LiftState* Context::runState = new RunState();
LiftState* Context::stopState = new StopState();
int _tmain(int argc, _TCHAR* argv[])
{
	Context context;	
	context.setLiftState(new CloseState());
	context.open();
	context.close();
	context.run();
	context.stop();
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值