Fork me on GitHub

设计模式中的车轮战-责任链模式

责任链模式在Android中的应用莫过于事件分发了,ViewGroup对事件分别给子View,从ViewTree的顶部至上而下地进行处理,直到事件被消化为止,这种方法在Android广播中也能看到

责任链模式的实现分为以下几个部分

请求者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public  class Request {
private Object object;
private int RequestLevel;
public Request(Object object,int requestLevel) {
this.object = object;
this.RequestLevel = requestLevel;
}

public Object getObject() {
return object;
}

public int getRequestLevel() {
return RequestLevel;
}
}

这里的object在实际开发当中我们可以换成其他自定义的对象,如Android中的Message和Handler那样

抽象处理者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public abstract class AbstractHandler {
private AbstractHandler nextHandler;
public final void handleRequest(Request request) {
if (getHandlerLevel() == request.getRequestLevel()) {
handle(request);
} else {
if (nextHandler != null) {
nextHandler.handleRequest(request);
} else {
System.out.println("No handler can handle it!");
}
}
}

public void setNextHandler(AbstractHandler nextHandler) {
this.nextHandler = nextHandler;
}

protected abstract int getHandlerLevel();

protected abstract void handle(Request request);
}

处理者

  1. 处理者1
1
2
3
4
5
6
7
8
9
10
public class Handler1 extends AbstractHandler {
@Override
protected void handle(Request request) {
System.out.println("handler1 handle it");
}
@Override
protected int getHandlerLevel() {
return 1;
}
}
  1. 处理者2
1
2
3
4
5
6
7
8
9
10
11
public class Handler2 extends AbstractHandler {
@Override
protected int getHandlerLevel() {
return 2;
}

@Override
protected void handle(Request request) {
System.out.println("handler2 handle it");
}
}

使用

1
2
3
4
5
6
7
8
9
public class Main {
public static void main(String[] args) {
AbstractHandler handler1 = new Handler1();
AbstractHandler handler2 = new Handler2();
handler1.setNextHandler(handler2);
Request request = new Request("request",2);
handler1.handleRequest(request);
}
}

这样处理事件就会沿着责任链一个个下去,直到被处理者处理或没有处理者为止