《Android源码设计模式》笔记——责任链模式

2016-12-27  本文已影响31人  Zeller

文章为阅读《Android源码设计模式解析与实战》的一些感悟与笔记,
有理解错误的地方,欢迎指正,要领略精髓还是要自己去阅读原�书。
原书作者的博客
Mr.Simple
aigestudio

定义

一个请求沿着一条“链”传递,直到该“链”上的某个处理者处理它为止。


责任链模式

责任链模式结构

具体实现

具体实现

代码实现

public abstract class AbstractHandler {
    protected AbstractHandler nextHandler;

    public final void handleRequest(AbstractRequest request) {
        if (getHandleLevel()==request.getRequestLevel()){
            handle(request);
        }else {
            if (nextHandler!=null){
                nextHandler.handle(request);
            }else {
                System.out.println("All of handler can not handle the request");
            }
        }
    }

    protected abstract int getHandleLevel();

    protected abstract void handle(AbstractRequest request);
}
public abstract class AbstractRequest {
    private Object obj;

    public AbstractRequest(Object obj) {
        this.obj = obj;
    }

    public Object getContent() {
        return obj;
    }

    public abstract int getRequestLevel();
}
public class Handler1 extends AbstractHandler {
    @Override
    protected int getHandleLevel() {
        return 1;
    }

    @Override
    protected void handle(AbstractRequest request) {
        System.out.println("Handler1 handle request:" + request.getRequestLevel());
    }
}  

  public class Request1 extends AbstractRequest {
    public Request1(Object obj) {
        super(obj);
    }
  
    @Override
    public int getRequestLevel() {
        return 1;
    }
}
public class Client {
    public static void main(String[] args) {
        AbstractHandler handler1 = new Handler1();
        AbstractHandler handler2 = new Handler2();
        AbstractHandler handler3 = new Handler3();

        handler1.nextHandler = handler2;
        handler2.nextHandler = handler3;

        AbstractRequest request1 = new Request1("Request1");
        AbstractRequest request2 = new Request2("Request2");
        AbstractRequest request3 = new Request3("Request3");

        handler1.handleRequest(request1);
        handler1.handleRequest(request2);
        handler1.handleRequest(request3);
    }
}

结果显而易见,handler1直接处理了request1,request2被handler2处理,request直到handler3才被处理。

总结

责任链模式能将请求者和处理者关系进行解耦,提高代码的灵活性。而缺点也显而易见,对链中请求处理者的遍历,如果处理者太多那么遍历必定会影响性能,特别是一些递归调用。

相关推荐

事件分发机制原理

上一篇 下一篇

猜你喜欢

热点阅读