【设计模式】责任者模式 -凯发k8官方网
凯发k8官方网
收集整理的这篇文章主要介绍了
【设计模式】责任者模式
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
责任链模式,是处理对象将请求沿着一条链,找到能处理此请求的对象。
责任链模式的例子
下面以数据从数据库取还是从缓存中取为例,代码描述责任链的样子。
全部责任者的父类,继承者实现抽象方法。
责任者之一:数据库。编号为1-9的文章由此责任者读取。
import java.util.hashmap; import java.util.map;public class databasehandler extends handler {@overridepublic string handle(integer docid) {if (this.getsuccessor() != null) {string result = this.getsuccessor().handle(docid);if (result != null) {return result;}}map责任者之一:缓存。编号为1-3的文章由此责任者读取。
import java.util.hashmap; import java.util.map;public class cachehandler extends handler {@overridepublic string handle(integer docid) {if (this.getsuccessor() != null) {string result = this.getsuccessor().handle(docid);if (result != null) {return result;}}map设置他们的责任关系,调用责任者
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 {// 上一级的责任者private handler 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 getsuccessor() {return successor;}public void setsuccessor(handler successor) {this.successor = successor;}} import java.util.hashmap; import java.util.map;public class databasehandler extends handler其他类略。
总结
以上是凯发k8官方网为你收集整理的【设计模式】责任者模式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: express4.x中的链式路由句柄
- 下一篇: identityserver4 实现 o