标签:
使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合。将系统连成一条线,并沿着这条线传递请求,直到有一个对象处理他为止。
package com.hml.responsiblity; public abstract class Handler { protected Handler successor; public Handler getSuccessor() { return successor; } public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handleRequest(int num); }
package com.hml.responsiblity; public class Handler1 extends Handler { @Override public void handleRequest(int num) { if (num < 10) { System.out.println(num); }else { successor.handleRequest(num); } } }
package com.hml.responsiblity; public class Handler2 extends Handler { @Override public void handleRequest(int num) { if (num < 30) { System.out.println(num); }else { successor.handleRequest(num); } } }
package com.hml.responsiblity; public class Handler3 extends Handler { @Override public void handleRequest(int num) { if (num > 30) { System.out.println(num); }else { successor.handleRequest(num); } } }
package com.hml.responsiblity; public class Test { public static void main(String[] args) { Handler h1 = new Handler1(); Handler h2 = new Handler2(); Handler h3 = new Handler3(); h1.setSuccessor(h2); h2.setSuccessor(h3); h1.handleRequest(1); h1.handleRequest(13); } }
职责链的好处是一个请求沿着一条链传递,直到有一个对象处理。避免了请求的发送者和接受者之间的耦合。
标签:
原文地址:http://www.cnblogs.com/heml/p/4655904.html