"Head First design mode" in the sample is very good, want to create a self-trading candy machine, candy machine has four states: insufficient investment, enough money to invest, sell candy, Candy sold out.
When the current state of a candy machine is in a different state, it is also different for the same action.
Traditional process-oriented programming would apply if-else to separate processes, logic hassles, and non-extensibility.
State mode: Agrees that an object changes its behavior when its internal state changes. The object appears to have changed its class.
The state mode focuses on state transitions, very often. For the state of an object, we are going to let this object include a state attribute, which records the detailed state of the object, and uses the branching structure to run different functions depending on the state. Just like the code above. It's like it said above. There are a number of similar branching statements in the class that are difficult to maintain and understand. The state mode eliminates the branching statements. Just as the factory pattern eliminates the branching statements of the simple factory pattern, the state processing is dispersed across the state subclasses. Each sub-class concentrates on a state, which makes the processing and transformation of the state clearly understood
State class, an abstract status class, that defines an interface to encapsulate the behavior associated with a particular state of a context.
Concretestate class, verbose state, each subclass implements a behavior related to a state of the context.
A context class that maintains an instance of a concretestate subclass. This instance defines the current state.
gives the framework. No longer implemented, better understood.
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;};
[C + + design mode] state mode