状态模式

#include <iostream>
#include <memory>

class Context;
class State {
public:
    virtual void handle1(Context *c) = 0;
    virtual void handle2(Context *c) = 0;
};

class Context {
public:
    Context(std::shared_ptr<State> s) : s_(s) {}
    void handle1() {
        std::cout << "In Context handle1." << std::endl;
        s_->handle1(this);
    }
    void handle2() {
        std::cout << "In Context handle2." << std::endl;
        s_->handle2(this);
    }
    void changeState(std::shared_ptr<State> s) { s_ = s; }
private:
    std::shared_ptr<State> s_;
};

class ConcreteState1 : public State {
public:
    void handle1(Context *c) override {
        std::cout << "In ConcreteState1 handle1." << std::endl;
    }
    void handle2(Context *c) override;
};

class ConcreteState2 : public State {
public:
    void handle1(Context *c) override {
        std::cout << "In ConcreteState2 handle1." << std::endl;
    }
    void handle2(Context *c) override {
        std::cout << "In ConcreteState2 handle2." << std::endl;
        std::shared_ptr<State> s1 = std::make_shared<ConcreteState1>();
        c->changeState(s1);
    }
};

void ConcreteState1::handle2(Context *c) {
    std::cout << "In ConcreteState1 handle2." << std::endl;
    std::shared_ptr<State> s1 = std::make_shared<ConcreteState2>();
    c->changeState(s1);
}

int main(int argc, char *argv[]) {
    std::shared_ptr<State> s = std::make_shared<ConcreteState1>();
    std::shared_ptr<Context> c = std::make_shared<Context>(s);
    c->handle1();
    c->handle2();
    c->handle1();
    c->handle2();
    c->handle2();
    return 1;
}

  

posted @ 2022-02-25 18:15  南乡水  阅读(17)  评论(0编辑  收藏  举报