当有多个对象可以处理同一请求,具体哪个对象要到运行时再定,客户端只需将请求提交到责任链上,无需关心谁处理
适用场景:采购审批子系统、OA中假条审批模块
1 public interface ChainHandler { 2 3 public void operator(); 4 5 } 6 7 public abstract class AbstractChainHandler { 8 9 private ChainHandler handler; 10 11 public ChainHandler getHandler(){ 12 return handler; 13 } 14 15 public void setHandler(ChainHandler handler){ 16 this.handler = handler; 17 } 18 19 } 20 21 public class MyChainHandler extends AbstractChainHandler implements ChainHandler { 22 23 private String name; 24 25 public MyChainHandler(String name) { 26 this.name = name; 27 } 28 29 @Override 30 public void operator() { 31 System.out.println(name + "开始处理"); 32 ChainHandler handler = getHandler(); 33 if(null != handler){ 34 handler.operator(); 35 }else{ 36 System.out.println("处理完毕"); 37 } 38 } 39 40 } 41 42 public class ChainMain { 43 44 public static void main(String[] args) { 45 MyChainHandler handler1 = new MyChainHandler("h1"); 46 MyChainHandler handler2 = new MyChainHandler("h2"); 47 MyChainHandler handler3 = new MyChainHandler("h3"); 48 MyChainHandler handler4 = new MyChainHandler("h4"); 49 50 handler1.setHandler(handler2); 51 handler2.setHandler(handler3); 52 handler3.setHandler(handler4); 53 54 handler1.operator(); 55 } 56 57 }
输出:
h1开始处理 h2开始处理 h3开始处理 h4开始处理 处理完毕