使用频率:★★★☆☆
一、什么是责任链模式
为请求创建了一个接收者对象的链,每个接收者都包含对另一个接收者的引用,当某个接受者不能处理该请求时,会将该请求转给下一个接受者处理;
二、补充说明
请求发送者与请求接受者解耦
应用例子:struts的拦截器,servlet的过滤器
三、角色
抽象请求处理者
具体请求处理者:包含下一个具体请求处理者的引用
客户端:请求发送者
四、例子,JAVA实现
说明:模拟一个村、镇、县的责任链关系请求
抽象处理者
package com.pichen.dp.behavioralpattern.chain; public abstract class Handler { protected Handler next; public abstract void handleRequest(String value); public Handler next() { return this.next; } public void setNext(Handler next) { this.next = next; } }
具体村、镇、县处理者
package com.pichen.dp.behavioralpattern.chain; public class VillageHandler extends Handler { /** * @see com.pichen.dp.behavioralpattern.chain.Handler#handleRequest() */ @Override public void handleRequest(String value) { if ("village".equals(value)) { System.out.println("VillageHandler: handled~"); } else { System.out.println("VillageHandler: pass~"); this.next.handleRequest(value); } } }
package com.pichen.dp.behavioralpattern.chain; public class TownHandler extends Handler { @Override public void handleRequest(String value) { if ("town".equals(value)) { System.out.println("VillageHandler: handled~"); } else { System.out.println("Town: pass~"); this.next.handleRequest(value); } } }
package com.pichen.dp.behavioralpattern.chain; public class CountyHandler extends Handler { @Override public void handleRequest(String value) { if ("county".equals(value)) { System.out.println("County: handled~"); } else if (this.next == null) { System.out .println("no next Handler, this request can not be handle~"); } else { System.out.println("County: pass~"); this.next.handleRequest(value); } } }
客户端:
package com.pichen.dp.behavioralpattern.chain; public class Main { public static void main(String[] args) { Handler villageHandler = new VillageHandler(); Handler townHandler = new TownHandler(); Handler countyHandler = new CountyHandler(); villageHandler.setNext(townHandler); townHandler.setNext(countyHandler); System.out.println("test county request:"); villageHandler.handleRequest("county"); System.out.println(" test city request:"); villageHandler.handleRequest("city"); } }
结果:
test county request: VillageHandler: pass~ Town: pass~ County: handled~ test city request: VillageHandler: pass~ Town: pass~ no next Handler, this request can not be handle~