【设计模式】责任者模式

责任链模式,是处理对象将请求沿着一条链,找到能处理此请求的对象。责任链模式的例子下面以数据从数据库取还是从缓存中取为例,代码描述责任链的样子。
全部责任者的父类,继承者实现抽象方法。public abstract class Handler { // 上一级的责任者 private Handler successor; public abstract String handle(Integer docId); /* 责任者的Getter、Setter */ public Handler getSuccessor() { return successor; } public void setSuccessor(Handler successor) { this.successor = successor; } }责任者之一:数据库。编号为1-9的文章由此责任者读取。import java.util.HashMap; import java.util.Map; public class DataBaseHandler extends Handler { @Override public String handle(Integer docId) { if (this.getSuccessor() != null) { String result = this.getSuccessor().handle(docId); if (result != null) { return result; } } Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 1; i <= 9; i++) { map.put(i, "文章" + i); } System.out.println(this.getClass().getName() + " do business."); return map.get(docId); } }责任者之一:缓存。编号为1-3的文章由此责任者读取。import java.util.HashMap; import java.util.Map; public class CacheHandler extends Handler { @Override public String handle(Integer docId) { if (this.getSuccessor() != null) { String result = this.getSuccessor().handle(docId); if (result != null) { return result; } } Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 1; i <= 3; i++) { map.put(i, "文章" + i); } System.out.println(this.getClass().getName() + " do business."); return map.get(docId); } }设置他们的责任关系,调用责任者public class HowToUse { public static void main(String[] args) { Handler dataBaseHandler = new DataBaseHandler(); Handler cacheHandler = new CacheHandler(); dataBaseHandler.setSuccessor(cacheHandler); System.out.println(dataBaseHandler.handle(3)); System.out.println(dataBaseHandler.handle(5)); } }日志如下:CacheHandler do business. 文章3 CacheHandler do business. DataBaseHandler do business. 文章5责任者的例子完毕。部分重构下面代码进行部分重构:判断环节进行封装公用,以及入参出参的泛型处理。 public abstract class Handler<I, O> { // 上一级的责任者 private Handler<I, O> successor; public abstract O handle(I i); public O handleFacade(I i) { O o = null; if (this.getSuccessor() != null) { o = this.getSuccessor().handleFacade(i); if (o != null) { return o; } } return this.handle(i); } /* 责任者的Getter、Setter */ public Handler<I, O> getSuccessor() { return successor; } public void setSuccessor(Handler<I, O> successor) { this.successor = successor; } }import java.util.HashMap; import java.util.Map; public class DataBaseHandler extends Handler<Integer, String> { @Override public String handle(Integer docId) { Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 1; i <= 9; i++) { map.put(i, "文章" + i); } System.out.println(this.getClass().getName() + " do business."); return map.get(docId); } }其他类略。

相关内容推荐