프로그래밍/GoF

[행동 패턴] - 책임 연쇄(Chain of responsibility)

MAKGA 2022. 1. 5. 19:04
320x100

구조

#include <iostream>
#include <string>

class Handler
{
public:
    Handler() = default;

    virtual void execute(std::string& request) = 0;
    virtual void setNext(Handler* next) = 0;
};

class BaseHandler : public Handler
{
public:
    BaseHandler() = default;

    virtual void execute(std::string& request) = 0;
    virtual void handleNext(std::string& request)
    {
        if (next_)
            next_->execute(request);
    }
    virtual void setNext(Handler* next) override
    {
        next_ = next;
    }

private:
    Handler* next_;
};

class HandlerImpl1 final : public BaseHandler
{
public:
    HandlerImpl1() = default;

    void execute(std::string& request) override final
    {
        if (request.compare("First"))
            handleNext(request);
        else
            std::cout << "HandlerImpl1" << std::endl;
    }
};

class HandlerImpl2 final : public BaseHandler
{
public:
    HandlerImpl2() = default;

    void execute(std::string& request) override final
    {
        if (request.compare("Second"))
            handleNext(request);
        else
            std::cout << "HandlerImpl2" << std::endl;
    }
};

class HandlerImpl3 final : public BaseHandler
{
public:
    HandlerImpl3() = default;

    void execute(std::string& request) override final
    {
        if (request.compare("Third"))
            handleNext(request);
        else
            std::cout << "HandlerImpl3" << std::endl;
    }
};

 

실행

int main()
{
    Handler* handler1 = new HandlerImpl1();
    Handler* handler2 = new HandlerImpl2();
    Handler* handler3 = new HandlerImpl3();

    handler1->setNext(handler2);
    handler2->setNext(handler3);

    std::string execute("First");
    handler1->execute(execute);

    execute = "Second";
    handler1->execute(execute);

    system("pause");

    return 0;
}

 

하나의 공통 기반 클래스를 상속받으면서 서로 다른 기능을 하는 파생클래스들을 서로 linked list처럼 엮어주고

입력된 조건을 만족하는 파생 클래스가 나올 때까지 리스트를 순회하며 실행하는 방식.


320x100