状态模式


#include 
#include 

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

class Context {
public:
    Context(std::shared_ptr 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 s) { s_ = s; }
private:
    std::shared_ptr 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 s1 = std::make_shared();
        c->changeState(s1);
    }
};

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

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