一.小结
- 定义:为请求创建了一个接收者对象的链,避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,并且沿着这条链传递请求,直到有对象式处理它为止。
- 优点:1.将请求与处理分开,降低耦合度。2.灵活性,增加新的处理类很容易。
- 缺点:1.处理链过长会影响性能 2.调试不很方便。
- 通用UML图:
二.例子
抗日剧中有句经典的台词,“营长没了,团长上,团长没了,师长上”,形成了一条营长->团长->师长的冲锋链,这里模拟下这个情景
-
开战请求
public interface IWar { // 营长级别 int LEVEL_REGIMENT = 2; // 团长级别 int LEVEL_BATTALION = 1; // 师长级别 int LEVEL_COMPANY = 0; int getLevel(); } public class War implements IWar { private int level; public War(int level) { this.level = level; } @Override public int getLevel() { return level; } }
-
战士处理抽象类
public abstract class Solider { // 军衔 private int level; // 下一级 private Solider next; public Solider(int level) { this.level = level; } // 职责 public abstract void task(); // 交给下一级处理 public void setNext(Solider next) { this.next = next; } // 封装责任链中请求处理 public void war(int level) { if (this.level == level) { task(); } else { if (next != null) { next.war(level); } } } }
-
具体的战士抽象类,形成一条处理链
public class Regiment extends Solider { public Regiment(int level) { super(level); } @Override public void task() { System.out.println("团长上"); } } public class Battalion extends Solider { public Battalion(int level) { super(level); } @Override public void task() { System.out.println("营长上"); } } public class Company extends Solider { public Company(int level) { super(level); } @Override public void task() { System.out.println("连长上"); } }
-
情景类
public static void main(String[] args) { // 开战请求 IWar war = new War(IWar.LEVEL_COMPANY); // 处理链 Regiment regiment = new Regiment(IWar.LEVEL_REGIMENT); Battalion battalion = new Battalion(IWar.LEVEL_BATTALION); Company company = new Company(IWar.LEVEL_COMPANY); regiment.setNext(battalion); battalion.setNext(company); // 执行请求 regiment.war(war.getLevel()); } }