State mode (State): Allows the behavior of an object to change when its internal state changes. The object looks like it has changed its class.
The state pattern mainly solves the situation when the conditional expression that controls the state transition of an object is too complex. By transferring the state judgment logic to a series of classes representing different states, complex judgments can be logicalized.
Pattern implementation:
[code]class Context; class State{ public: virtual void Handle(Context *pContext) = 0; }; class ConcreteStateA: public State{ public: virtual void Handle(Context *pContext){ std::cout << "I'm concretestateA.\n"; } }; class ConcreteStateB: public State{ public: virtual void Handle(Context *pContext){ std::cout << "I'm concretestateB.\n"; } }; class Context{ public: Context(State *state):pState(state){} void Request(){ if(pState){ pState->Handle(this); } } void ChangeState(State *pstate){ pState = pstate; } private: State *pState; };
Client
[code]int main(){ State *pState = new ConcreteStateA(); Context *context = new Context(pState); context->Request(); //Output: I'm concretestateA. State *pState2 = new ConcreteStateB(); context->ChangeState(pState2); context->Request(); //Output: I'm concretestateB. if(pState){ delete pState; pState = NULL; } if(pState2){ delete pState2; pState2 = NULL; } if(context){ delete context; context = NULL; } return 0; }
The above is the content of the C++ design pattern brief understanding of the state pattern. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!