C++ state mode of design mode 20 (including sample code)

The State pattern is a behavioral design pattern that allows an object to change its behavior when its internal state changes, appearing to change the object's class.

Here is a sample code implementing the state pattern in C++:

#include <iostream>
// 抽象状态类:定义了所有具体状态类的接口
class State {
    
    
public:
    virtual ~State() {
    
    }
    virtual void Handle() = 0;
};
// 具体状态类:实现了抽象状态类的接口
class ConcreteStateA : public State {
    
    
public:
    virtual ~ConcreteStateA() {
    
    }
    virtual void Handle() override {
    
    
        std::cout << "Concrete State A" << std::endl;
    }
};
class ConcreteStateB : public State {
    
    
public:
    virtual ~ConcreteStateB() {
    
    }
    virtual void Handle() override {
    
    
        std::cout << "Concrete State B" << std::endl;
    }
};
// 上下文类:维护一个具体状态类的实例,并定义了一个接口供外部调用
class Context {
    
    
public:
    Context(State* state) : state_(state) {
    
    }
    ~Context() {
    
    
        delete state_;
    }
    void Request() {
    
    
        state_->Handle();
    }
    void ChangeState(State* state) {
    
    
        delete state_;
        state_ = state;
    }
private:
    State* state_;
};
int main() {
    
    
    // 创建具体状态对象
    ConcreteStateA* state_a = new ConcreteStateA();
    ConcreteStateB* state_b = new ConcreteStateB();
    // 创建上下文对象,并设置初始状态为 ConcreteStateA
    Context context(state_a);
    // 调用上下文对象的接口,输出 "Concrete State A"
    context.Request();
    // 改变上下文对象的状态为 ConcreteStateB
    context.ChangeState(state_b);
    // 再次调用上下文对象的接口,输出 "Concrete State B"
    context.Request();
    return 0;
}

In the above code, we first define an abstract state class State, which defines the interfaces of all concrete state classes. Next, we created two concrete state classes, ConcreteStateA and ConcreteStateB, which implement the interface of the abstract state class. Finally, we define a context class Context, which maintains an instance of a specific state class and defines an interface for external calls.

In the main() function, we create two concrete state objects state_a and state_b, and use state_a as the initial state, then create a context object context, and call its interface Request() to output "Concrete State A". Next, we change the state of the context object to state_b, call the Request() interface again, and output "Concrete State B".

The advantage of the State pattern is that it localizes the behavior associated with a particular state and makes state transitions explicit. At the same time, the state mode also allows us to simplify the complexity of conditional statements, making the code clearer and easier to understand. However, the state pattern may lead to an increase in the number of classes, which increases the complexity of the code.

Guess you like

Origin blog.csdn.net/dica54dica/article/details/130021568