定义
使用场景
- 弱化请求者与处理者的关系。
- 举例:审批链:三天内假直系领导审批,七天内假期副总审批,两周内总经理审批。
UML图

代码实现
public abstract class Handler {
private Handler next;
public Handler setNext(Handler next){
this.next = next;
return next;
}
public void doResolve(Integer vacation){
if(resolve(vacation)){
System.out.println("审批成功");
}else if(next != null){
next.doResolve(vacation);
}else {
System.out.println("审批未通过");
}
}
protected abstract boolean resolve(Integer vacation);
}
public class LeadHandler extends Handler {
@Override
public boolean resolve(Integer vacation) {
if(vacation <= 3 && vacation > 0){
System.out.println("直系领导同意!");
return true;
}
return false;
}
}
public class ManagerHandler extends Handler {
@Override
protected boolean resolve(Integer vacation) {
if(vacation <= 7){
System.out.println("经理同意");
return true;
}
return false;
}
}
public class BossHandler extends Handler {
@Override
protected boolean resolve(Integer vacation) {
if(vacation <= 14){
System.out.println("老板同意");
return true;
}
return false;
}
}
public class Client {
public static void main(String[] args) {
Handler handler = new LeadHandler();
handler.setNext(new ManagerHandler()).setNext(new BossHandler());
handler.doResolve(7);
handler.doResolve(10);
handler.doResolve(16);
}
}
总结
- 将不能处理的事情交给别人去处理。各个对象专注于自己的事情。
- 符合里氏替换原则,职责链的下一级可以动态变换。
- 弱化请求者与处理者的关系是一个好处,同时也会带来处理延迟。