设计模式——责任链模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public abstract class Handler<T> {

protected Handler<T> next;

private void next(Handler<T> next) {
this.next = next;
}

public abstract void doHandler(T data);

public static class Builder<T> {
private Handler<T> head;
private Handler<T> tail;

public Builder<T> addHandler(Handler<T> handler) {
if (this.head == null) {
this.head = this.tail = handler;
return this;
}
this.tail.next(handler);
this.tail = handler;
return this;
}

public Handler<T> build() {
return this.head;
}
}
}
1
2
3
4
5
6
7
8
9
public class AHandler extends Handler {
@Override
public void doHandler(Object data) {
System.out.println("A:" + data.toString());
if (Objects.nonNull(next)) {
next.doHandler(data);
}
}
}
1
2
3
4
5
6
public class BHandler extends Handler{
@Override
public void doHandler(Object data) {
System.out.println("B:" + data.toString());
}
}
1
2
3
4
5
6
7
8
9
public class Test {

public static void main(String[] args) {
Handler.Builder builder = new Handler.Builder<>()
.addHandler(new AHandler())
.addHandler(new BHandler());
builder.build().doHandler("当我遇上你");
}
}