1 public class ChainTest { 2 private static Handler handler1,handler2; 3 public static void main(String[] args) { 4 handler1 = new ConcreteHandler(); 5 handler2 = new ConcreteHandler(); 6 handler1.setSuccessor(handler2); 7 handler1.handleRequest(); 8 } 9 10 } 11 //抽象處理者 12 abstract class Handler{ 13 protected Handler successor; 14 //調用此處理方法處理請求 15 public abstract void handleRequest(); 16 //賦值方法,調用此方法設定下家 17 public void setSuccessor(Handler successor){ 18 this.successor = successor; 19 } 20 //取值方法 21 public Handler getSuccessor(){ 22 return successor; 23 } 24 } 25 26 //具體處理者 27 class ConcreteHandler extends Handler{ 28 29 @Override 30 public void handleRequest() { 31 if(getSuccessor()!=null){ 32 System.out.println("The request is passed to "+ getSuccessor()); 33 getSuccessor().handleRequest(); 34 }else{ 35 System.out.println("The request is handled here"); 36 } 37 } 38 39 }