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

来源:互联网 发布:我的世界linux服务端 编辑:程序博客网 时间:2024/06/04 19:58

用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;}




0 0