责任链模式

#include <iostream>
#include <memory>

class Handler {
public:
    virtual void handle(int data) = 0;
    virtual void setNextHandler(std::shared_ptr<Handler> nh) { this->nh = nh; }
protected:
    std::shared_ptr<Handler> nh = nullptr;
};

class AbstractHandler : public Handler {
public:
    void handle(int data) override {
        if (this->nh){ return this->nh->handle(data); }
        std::cout << "In AbstractHandler handle(). Didn't handle the data." << std::endl;
    }
};

class ConcreteHandler1 : public AbstractHandler {
public:
    void handle(int data) override {
        if (data == 1) {
            std::cout << "In ConcreteHandler1 handle()." << std::endl;
        } else {
            AbstractHandler::handle(data);
        }
    }
};

class ConcreteHandler2 : public AbstractHandler {
public:
    void handle(int data) override {
        if (data == 2) {
            std::cout << "In ConcreteHandler2 handle()." << std::endl;
        } else {
            AbstractHandler::handle(data);
        }
    }
};

int main(int argc, char *argv[]) {
    AbstractHandler h;
    std::shared_ptr<AbstractHandler> h1 = std::make_shared<ConcreteHandler1>();
    std::shared_ptr<AbstractHandler> h2 = std::make_shared<ConcreteHandler2>();
    h.setNextHandler(h1);
    h1->setNextHandler(h2);
    h.handle(1);
    h.handle(2);
    h.handle(3);
    return 1;
}

  

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