设计模式--状态模式

    技术2022-07-10  92

    状态模式:属于行为型模式基本原理:类的行为是基于它的状态改变的主要流程:             1.创建一个对象,该对象可以使用状态改变行为             2.创建状态类,对象可以使用这些状态来进行不同的行为

    #include <iostream> #include <string> using namespace std; class State; //创建一个对象,该对象受状态控制 class Context { private: State *state; public: Context() { this->state = NULL; } void setState(State *state) { this->state = state; } State *getState() { return this->state; } }; //创建状态的基类 class State { public: virtual void doAction(Context *context) = 0; virtual string toString() = 0; }; //创建状态类不同的派生类 class StartState : public State { public: void doAction(Context *context)//对象使用了该状态 { cout<<"Player is in start state"<<endl; context->setState(this); } string toString() { return "Start State"; } }; class StopState: public State { public: void doAction(Context *context)//对象使用了该状态 { cout<<"Player is in stop state"<<endl; context->setState(this); } string toString() { return "Stop State"; } }; int main() { Context *context = new Context(); StartState *startState = new StartState(); startState->doAction(context); cout<<"now state : "<<context->getState()->toString()<<endl; StopState *stopState = new StopState(); stopState->doAction(context); cout<<"now state : "<<context->getState()->toString()<<endl; return 0; }

     

    Processed: 0.047, SQL: 9