State mode: When an object's internal state changes to allow its behavior to change, the object looks like it has changed its class.
State mode mainly solves the situation when the conditional expression that controls an object state transition is too complex. By transferring the judgment logic of the state to a series of classes representing different States, complex judgments can be logically made.
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):p 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 C + + design mode of shallow knowledge of the content of State mode, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!