责任链模式

一、模式名

责任链模式, Chain of Responsibility

二、解决的问题

责任链模式,类似于“踢皮球”,在日常生活中,我们经常可以看到“踢皮球”现象,比如去政府办事,可能需要找几个部门,才能解决问题,因为他们都会告诉你,他们不负责这个事,需要找谁谁谁的,这种现象就是责任链模式。

责任链模式的优点是解耦请求方和处理方,能让请求方和处理方都成为灵活可扩展的组件。

三、解决方案

责任链模式的UML图如下所示

clipboard

实例代码如下:

public class ChainOfResponsibilityExer {
    public static void main(String[] args) throws Exception {
        VerifyHandler nullHandler = new NullHandler("123");
        LengthHandler lengthHandler = new LengthHandler("122334");
        nullHandler.setNext(lengthHandler);
        nullHandler.execute();
    }
}
abstract class VerifyHandler {
    private VerifyHandler next;
    private String value;
    public VerifyHandler(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }
    public VerifyHandler setNext(VerifyHandler next) {
        this.next = next;
        return this.next;
    }
    public VerifyHandler getNext() {
        return next;
    }
    void execute() throws Exception {
        handle();
        if (next != null) {
            next.handle();
        }
    }
    abstract void handle() throws Exception;
}
class NullHandler extends VerifyHandler {
    public NullHandler(String val) {
        super(val);
    }
    
    @Override 
    void handle() throws Exception {
        if (getValue() == null) {
            throw new Exception("null");
        }
    }
}
class LengthHandler extends VerifyHandler {
    public LengthHandler(String val) {
        super(val);
    }
 
    @Override 
    void handle() throws Exception {
        if (getValue().length() > 5) {
            throw new Exception("too long");
        }
    }
}

常见使用场景:

1. 参数校验器

原文地址:https://www.cnblogs.com/glsy/p/11167538.html