Condivisione della tecnologia

Modalità di stato "C Design Pattern".

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

I. Introduzione

Penso che la comprensione più elementare del modello statale dovrebbe essere sufficiente, se viene effettivamente utilizzata, dovrebbe esserloBoost.MSMmacchina statale.

Il codice pertinente può essere trovato qui. Se ti aiuta, assegnagli una stella!AidenYuanDev/modelli_di_progettazione_nel_Cpp_moderno_20

2. Realizzazione

1. Diagramma delle classi UML

modalità statale

2. Realizzazione

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56