设计模式 - State
意图:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
class Context; class State { public: State() {} virtual ~State() {} virtual void Operation(Context* context) = 0; }; class ConcreteStateA: public State { public: ConcreteStateA() {} ~ConcreteStateA() {} void Operation(Context* context); }; class ConcreteStateB: public State { public: ConcreteStateB() {} ~ConcreteStateB() {} void Operation(Context* context); }; class Context { public: Context() { this->stateA = new ConcreteStateA(); this->stateB = new ConcreteStateB(); this->current_state = this->stateA; } ~Context() { delete this->stateA; delete this->stateB; } void Request() { current_state->Operation(this); } private: friend class State; friend class ConcreteStateA; friend class ConcreteStateB; void ChangeState(State* state) { this->current_state = state; } State* stateA; State* stateB; State* current_state; }; void ConcreteStateA::Operation(Context* context) { cout<<"ConcreteStateA::Operation()"<<endl; context->ChangeState(context->stateB); } void ConcreteStateB::Operation(Context* context) { cout<<"ConcreteStateB::Operation()"<<endl; context->ChangeState(context->stateA); }