《C++设计模式》状态模式

文章目录

一、前言

状态模式理解最基本上的我觉得应该也是够用了,实际用的话,也应该用的是Boost.MSM状态机。

相关代码可以在这里,如有帮助给个star!AidenYuanDev/design_patterns_in_modern_Cpp_20

二、实现

一、UML类图

二、实现

c 复制代码
#include <iostream>
#include <memory>
using namespace std;

class Light_Switch;
class On_State;
class Off_State;
class State {
public:
    virtual void on(Light_Switch* ls) = 0;![请添加图片描述](https://i-blog.csdnimg.cn/direct/9c069a22ebae485d8dbd3f084c658e5d.png)

    virtual void off(Light_Switch* ls) = 0;
};

class On_State : public State {
public:
    On_State() { cout << "灯打开了" << endl; }
    void on(Light_Switch* ls) override {}
    void off(Light_Switch* ls) override;
};

class Off_State : public State {
public:
    Off_State() { cout << "灯灭了" << endl; }
    void on(Light_Switch* ls) override;
    void off(Light_Switch* ls) override {}
};

class Light_Switch {
private:
    shared_ptr<State> state_;

public:
    Light_Switch() : state_(make_shared<Off_State>()) {}
    void set_state(shared_ptr<State> state) { state_ = std::move(state); }
    void on() { state_->on(this); }
    void off() { state_->off(this); }
};

void On_State::off(Light_Switch* ls) {
    cout << "按下关灯键" << endl;
    ls->set_state(make_shared<Off_State>());
}

void Off_State::on(Light_Switch* ls) {
    cout << "按下开灯键" << endl;
    ls->set_state(make_shared<On_State>());
}

int main() {
    auto ls = make_shared<Light_Switch>();
    ls->on();
    ls->off();
    ls->on();
    return 0;
}
相关推荐
saltymilk16 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥16 小时前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
李广坤1 天前
工厂模式
设计模式