A brief introduction to state pattern in C++ design patterns

黄舟
Release: 2017-01-17 13:34:08
Original
1539 people have browsed it

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&#39;m concretestateA.\n";
    }
};

class ConcreteStateB: public State{
public:
    virtual void Handle(Context *pContext){
        std::cout << "I&#39;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;
};
Copy after login

Client

[code]int main(){
    State *pState = new ConcreteStateA();
    Context *context = new Context(pState);
    context->Request();  //Output: I&#39;m concretestateA.

    State *pState2 = new ConcreteStateB();
    context->ChangeState(pState2);
    context->Request();  //Output: I&#39;m concretestateB.

    if(pState){
        delete pState;
        pState = NULL;  
    }
    if(pState2){
        delete pState2;
        pState2 = NULL;
    }
    if(context){
        delete context;
        context = NULL;
    }
    return 0;
}
Copy after login

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)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template