Chain Of Responsibility

职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合度。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

接收者和发送者都没有对方的明确信息,且链中的对象自己也并不知道链的结构。结果是职责链可简化对象的相互连接,它们仅需保持一个指向后继者的引用,而不需保持它所有的候选者的引用。

随时可增加或修改处理一个请求的的结构。增强了给对象指派职责的灵活性。

Chain Of Responsibility

 1 //定义一个处理请示接口

 2 public abstract class Handler {

 3 

 4     protected Handler successor;

 5     

 6     public void setSuccessor(Handler successor){

 7     this.successor = successor;

 8     }

 9     

10     public abstract void handleRequest(int request);

11     

12 }
 1 //具体处理类,处理它所负责的请求,可访问它的后继者,如果可处理该请求就处理,否则将请求转发到它的后继者。

 2 class ConcreteHandler1 extends Handler {

 3 

 4     @Override

 5     public void handleRequest(int request) {

 6     //请求数在 0-10 之间有权处理,否则转到下一位

 7     if(request >=0 && request < 10){

 8         System.out.println("request - " + request);

 9         System.out.println("deal - " + ConcreteHandler1.class.getName());

10     }else{

11         successor.handleRequest(request);

12     }

13     }

14     

15 }

16 

17 class ConcreteHandler2 extends Handler {

18 

19     @Override

20     public void handleRequest(int request) {

21     //请求数在 10-20 之间有权处理,否则转到下一位

22     if(request >= 10 && request < 20){

23         System.out.println("request - " + request);

24         System.out.println("deal - " + ConcreteHandler2.class.getName());

25     }else{

26         successor.handleRequest(request);

27     }

28     }

29     

30 }

31 

32 class ConcreteHandler3 extends Handler {

33 

34     @Override

35     public void handleRequest(int request) {

36     if(request >=20 && request < 30){

37         System.out.println("request - " + request);

38         System.out.println("deal - " + ConcreteHandler3.class.getName());

39     }else{

40         successor.handleRequest(request);

41     }

42     }

43     

44 }
 1 public static void main(String[] args) {

 2     Handler h1 = new ConcreteHandler1();

 3     Handler h2 = new ConcreteHandler2();

 4     Handler h3 = new ConcreteHandler3();

 5     

 6     //设置职责链的上家和下家

 7     h1.setSuccessor(h2);

 8     h2.setSuccessor(h3);

 9     h3.setSuccessor(h1);

10     

11     int[] requests = {1,5,15,20};

12     

13     for(int i : requests){

14         h1.handleRequest(i);

15     }

16 }

打印结果:

request - 1
deal - org.chain.ConcreteHandler1
request - 5
deal - org.chain.ConcreteHandler1
request - 15
deal - org.chain.ConcreteHandler2
request - 20
deal - org.chain.ConcreteHandler3

你可能感兴趣的:(chain)