行为设计模式之状态模式

文章目录

概述

定义

状态模式(state pattern)的定义: 允许一个对象在其内部状态改变时改变它的行为。 对象看起来似乎修改了它的类。

状态模式就是用于解决系统中复杂对象的状态转换以及不同状态下行为的封装问题.。状态模式将一个对象的状态从该对象中分离出来,封装到专门的状态类中(用类来表示状态) ,使得对象状态可以灵活变化。

结构图

  • 上下文信息类(Context):实际上就是存储当前状态的类,对外提供更新状态的操作。在该类中维护着一个抽象状态接口State实例,这个实例定义当前状态.

  • 抽象状态类(State):可以是一个接口或抽象类,用于定义声明状态更新的操作方法有哪些,具体实现由子类完成。

  • 具体状态类(StateA 等):实现抽象状态类定义的方法,根据具体的场景来指定对应状态改变后的代码实现逻辑。

2.代码示例

cpp 复制代码
// 抽象状态类
class State {
public:
    virtual void Handle(std::string input, std::shared_ptr<State> &currentState) = 0;
};

// 具体状态A
class StateA : public State {
public:
    void Handle(std::string input, std::shared_ptr<State> &currentState) override {
        if (input == "A") {
            std::cout << "StateA: Handle input A." << std::endl;
        } else if (input == "B") {
            std::cout << "StateA: Transition to StateB." << std::endl;
            currentState = std::make_shared<StateB>();
        } else {
            std::cout << "StateA: Invalid input." << std::endl;
        }
    }
};

// 具体状态B
class StateB : public State {
public:
    void Handle(std::string input, std::shared_ptr<State> &currentState) override {
        if (input == "B") {
            std::cout << "StateB: Handle input B." << std::endl;
        } else if (input == "C") {
            std::cout << "StateB: Transition to StateC." << std::endl;
            currentState = std::make_shared<StateC>();
        } else {
            std::cout << "StateB: Invalid input." << std::endl;
        }
    }
};

// 具体状态C
class StateC : public State {
public:
    void Handle(std::string input, std::shared_ptr<State> &currentState) override {
        if (input == "C") {
            std::cout << "StateC: Handle input C." << std::endl;
        } else if (input == "A") {
            std::cout << "StateC: Transition to StateA." << std::endl;
            currentState = std::make_shared<StateA>();
        } else {
            std::cout << "StateC: Invalid input." << std::endl;
        }
    }
};

// 上下文类,维护当前状态并执行请求
class Context {
private:
    std::shared_ptr<State> currentState;
public:
    Context(std::shared_ptr<State> initialState) : currentState(initialState) {}
    void Request(std::string input) {
        currentState->Handle(input, currentState);
    }
};

小结

这篇文章主要说了状态模式的定义,结构图,以及代码示例;这些都很常用的,不管是生活中,还是开发中,都是这样的。道理呢,往往很简单,看看代码示例,再想想现实生活,可能就理解了。OK,翻篇。

相关推荐
刷帅耍帅2 小时前
设计模式-享元模式
设计模式·享元模式
刷帅耍帅2 小时前
设计模式-模版方法模式
设计模式
刷帅耍帅3 小时前
设计模式-桥接模式
设计模式·桥接模式
MinBadGuy4 小时前
【GeekBand】C++设计模式笔记5_Observer_观察者模式
c++·设计模式
刷帅耍帅5 小时前
设计模式-生成器模式/建造者模式Builder
设计模式·建造者模式
蜡笔小新..1 天前
【设计模式】软件设计原则——开闭原则&里氏替换&单一职责
java·设计模式·开闭原则·单一职责原则
性感博主在线瞎搞1 天前
【面向对象】设计模式概念和分类
设计模式·面向对象·中级软件设计师·设计方法
lucifer3111 天前
JavaScript 中的组合模式(十)
javascript·设计模式
lucifer3111 天前
JavaScript 中的装饰器模式(十一)
javascript·设计模式
蜡笔小新..1 天前
【设计模式】软件设计原则——依赖倒置&合成复用
设计模式·依赖倒置原则·合成复用原则