职责链模式

一个请求,沿链传递直到有一个Handler对象处理它.
接收者和发送者都没有对方的明确信息,且链中的对象自己也不知道链的结构.结果是职责链可以简化对象的相互连接,它们仅需保持一个指向其后继者的引用,而不需保持它所有的候选接收者的引用.
随时地增加或修改处理一个请求的结构.增强了给对象指派职责的灵活性.

注意: 一个请求极有可能到了链的末端都得不到处理,或者因为没有正确配置而得不到处理.这是很糟糕的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package chain.of.responsibility;

/**
* Created by hero on 17-2-20.
*/
public abstract class Manager {
protected Manager superior;

public void setSuperior(Manager superior) {
this.superior = superior;
}

public abstract void handle(int money);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package chain.of.responsibility;

/**
* Created by hero on 17-2-20.
*/
public class Minister extends Manager {

@Override
public void handle(int money) {
if (money < 100) {
System.out.println("ok, give you.");
} else {
if (superior != null) {
superior.handle(money);
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
package chain.of.responsibility;

/**
* Created by hero on 17-2-20.
*/
public class President extends Manager {

@Override
public void handle(int money) {
System.out.println("没有我管不了,OK.");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package chain.of.responsibility;

/**
* Created by hero on 17-2-20.
*/
public class Main {
public static void main(String[] args) {
Minister minister = new Minister();
President president = new President();
minister.setSuperior(president);

int[] money = {10, 20, 120};

for (int m : money) {
minister.handle(m);
}
}
}