初识 | 责任链模式

       顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。

       目的: 避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。

下面通过代码来认识一下这种设计思想

需求设定:三种不同的处理级别,每种级别处理自己对应的消息,不能越级处理。

具体实现:

(1)创建一个抽象类,因为我们需要让对象成一条链传递运行,利用继承的特性统一处理传递过程,此处也是责任链模式的关键所在,写法大同小异,可以根据自己的需求做变动。

public abstract class ChainHandler {

    protected int level;

    protected ChainHandler nextHandler;

    // 设置传递的下一个对象
    public void setNextHandler(ChainHandler nextHandler){
        this.nextHandler = nextHandler;
    }

    // 传递级别的判断和消息处理(此处可根据具体场景做改动)
    public void handlerMessage(int level, String message){
        if (this.level == level){
            handlerProcess(message);
            return;
        }
        if (nextHandler != null){
            nextHandler.handlerMessage(level, message);
        }
    }

    // 不同对象的具体消息处理过程
    abstract protected void handlerProcess(String message);
}

(2)创建扩展了该抽象类的不同实体,设置其级别信息和处理过程,通过构造函数直接设置(可根据业务自行调整)

public class ChainHandlerOneImpl extends ChainHandler {

    public ChainHandlerOneImpl(){
        level = 1;
    }

    @Override
    protected void handlerProcess(String message) {
        System.out.println("这里是一级处理过程");
        System.out.println("处理信息为:" + message);
    }
}
public class ChainHandlerTwoImpl extends ChainHandler {

    public ChainHandlerTwoImpl(){
        level = 2;
    }

    @Override
    protected void handlerProcess(String message) {
        System.out.println("这里是二级处理过程");
        System.out.println("处理信息为:" + message);
    }
}
public class ChainHandlerThrImpl extends ChainHandler {

    public ChainHandlerThrImpl(){
        level = 3;
    }

    @Override
    protected void handlerProcess(String message) {
        System.out.println("这里是三级处理过程");
        System.out.println("处理信息为:" + message);
    }
}

(3)创建不同级别的处理对象,并且设置其对应的下一个处理对象,完成链的组成

ChainHandler oneChain = new ChainHandlerOneImpl();
ChainHandler twoChain = new ChainHandlerTwoImpl();
ChainHandler thrChain = new ChainHandlerThrImpl();

oneChain.setNextHandler(twoChain);
twoChain.setNextHandler(thrChain);

(4)传入参数,并且执行,为了更加直观,将不同的条件和对应的输出结果相应贴出

oneChain.handlerMessage(1, "一级处理消息");

  

oneChain.handlerMessage(2, "二级处理消息");

  

oneChain.handlerMessage(3, "三级处理消息");

  

        这样就完成了整个责任链模式的开发,整个过程保证了调用是相同的入口,根据不同的参数完成了条件的筛选,并且代码结构清晰,阅读性强,后期功能扩展起来也非常方便,希望大家可以有所收获。

猜你喜欢

转载自blog.csdn.net/a_ll1203/article/details/81064049