The example in head first design mode is very good, want to create an automatic trading candy machine, candy machine has four states: insufficient investment money, enough money to sell, Candy sold, Candy sold out. When the current state of a candy machine is in a different state, its response to the same action is different. Traditional process-oriented programming can apply if-else to different states, logic is cumbersome and not extensible.
State mode: Allows an object to change its behavior when its internal state changes. The object appears to have modified its class. State mode is focused on state transitions, many times, for an object's state, we are to let the object contains a state of the property, the State property records the specific state of the object, depending on the state of the use of branching structure to perform different functions, like the above code to deal with; There are a number of similar branching statements in the class that are difficult to maintain and understand. The state mode eliminates branching statements, just as the factory pattern eliminates the branching statements of the simple factory pattern, dispersing state processing across state subclasses, each of which centralizes a state so that the processing and transformation of the state is clear
State class, an abstract status class, that defines an interface to encapsulate the behavior associated with a particular state of a context.
The Concretestate class, the specific state, each subclass implements a behavior related to a state of the context.
The context class, which maintains an instance of the Concretestate subclass that defines the current state.
Give the frame, no longer achieve, better understanding.
Class Context;class State{public: virtual void Handle (context* pContext) =0; ~state ();p rotected: State ();p rivate:};class concretestatea:public state{public: Concretestatea (); ~concretestatea (); virtual void Handle (context* pContext);p rotected:private:};class concretestateb:public state{public: Concretestateb (); ~concretestateb (); virtual void Handle (context* pContext);p rotected:private:};class concretestatec:public state{public: Concretestatec (); ~concretestatec (); virtual void Handle (context* pContext);p rotected:private:};class context{public: Context (state* pState); ~context (); void Request (); void Changestate (state* pState);p rotected:private: state* _state;};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[C + + design mode] state mode