职责链模式
使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合。将系统连成一条线,并沿着这条线传递请求,直到有一个对象处理他为止。
Handler
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); }
Handler1
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); } } }
Handler2
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); } } }
Handler3
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); } } }
Test
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); } }
职责链的好处是一个请求沿着一条链传递,直到有一个对象处理。避免了请求的发送者和接受者之间的耦合。
时间: 2024-08-08 09:40:28