设计模式——职责链模式

一、说明
职责链模式:
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之前的耦合关系,将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。

职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无需关心请求的处理细节和请求的传递,所有职责链将请求的发送者和请求的处理者解耦了。
二、代码

#ifndef FORM_H
#define FORM_H

enum Level{
    level_one,
    level_two,
    level_three
};

class handler
{
public:
    handler(handler* parent){
        m_pParent = parent;
    }
    virtual ~handler();
    virtual void handlerReq(Level level) = 0;
    handler *m_pParent;
};
class handlerOne : public handler
{
public:
    handlerOne(handler *parent = nullptr);
    ~handlerOne();
    void handlerReq(Level level) override;
};
class handlerTwo: public handler
{
public:
    handlerTwo(handler *parent);
    ~handlerTwo();
    void handlerReq(Level level) override;
};
class handlerThree : public handler
{
public:
    handlerThree(handler *parent);
    ~handlerThree();
    void handlerReq(Level level) override;
};
class test
{
public:
    test();
};

#endif // FORM_H

#include "form.h"
#include "ui_form.h"

handlerOne::handlerOne(handler *parent):
    handler(parent)
{

}

handlerOne::~handlerOne()
{

}

void handlerOne::handlerReq(Level level)
{
    if(level_one == level){
        //handler one
    }else{
        m_pParent->handlerReq(level);
    }
}

handlerTwo::handlerTwo(handler *parent):
    handler(parent)
{

}

handlerTwo::~handlerTwo()
{

}

void handlerTwo::handlerReq(Level level)
{
    if(level_two == level){
        //handler two
    }else{
        m_pParent->handlerReq(level);
    }
}

handlerThree::handlerThree(handler *parent):
    handler(parent)
{

}

handlerThree::~handlerThree()
{

}

void handlerThree::handlerReq(Level level)
{
    if(level_three == level){
        //handler three
    }else{
        m_pParent->handlerReq(level);
    }
}

test::test()
{
    handlerOne *one = new handlerOne();
    handlerTwo *two = new handlerTwo(one);
    handlerThree *three = new handlerThree(two);

    three->handlerReq(level_one);
    delete three;
    delete two;
    delete one;
}

你可能感兴趣的:(【设计模式】)