Design Pattern-status pattern (with code)
The State mode allows an object to change its behavior when its internal state changes. This object seems to have changed the class.
Main purpose:
The State mode mainly solves the problem where the expression controlling the state transition of an object is too complex, and transfers the State judgment logic to some column classes that indicate different states.
:
The essence of this figure is the switching between States, simulating a scenario for us. Context is an environment, and we do different things for the environment according to the current state, if the current environment does not conform to our status, we can change it.
If we don't use this state mode, then the consequence is that there are a large number of if and else judgments in a method. The method that is too long is enough to attract our attention.
Put specific State-related behaviors into an object. Because all State-related code exists in a ConcreteState, we can add a class to add a new state.
The State mode reduces mutual dependencies by distributing various State transfer logics to sub-classes of State.
The advantage of the State mode is to localize the texts related to a specific State and separate the behaviors of different States.
Let's take a look at the code I wrote:
# Include
Using namespace std; class Context; class AbstractState; class ConcreteStateB; class ConcreteStateA; class AbstractState {public: virtual void handle (Context & context) = 0 ;}; class Context {public: abstractState * state; int hour; Context (AbstractState * state): state (state) {} virtual void request () {state-> handle (* this );}}; class ConcreteStateB: public AbstractState {public: virtual void handle (Context & context) {if (context. hour> = 12) {cout <all over 12 points. What else can I do? <endl ;}}; class ConcreteStateA: public AbstractState {public: virtual void handle (Context & context) {if (context. hour <12) {cout
First, we do not care about memory leakage. Here, our State class can access the internal members of the Context and perform proper operations based on their members and our status, if one day we need to add or subtract states, we can directly delete or add classes. if it is an if or else structure, it violates the open-closed principle, there is also a single responsibility principle.