设计模式--职责链模式
来源:互联网 发布:java 逐层截取路径 编辑:程序博客网 时间:2024/05/19 02:01
1 职责链模式适用于将请求以链的形式传递到各个处理者,从而避免请求的发送者和接受者之间的耦合,将请求连成一条线。如下一个例子,有三个处理请求的类,每一个均处理不同的情况。
处理抽象方法:
public abstract class Handler { protected Handler handler; public void setHandler(Handler handler) { this.handler = handler; } // 处理请求 protected abstract void handlerRequest(Integer request);}
处理请求类:
public class HandlerRequest01 extends Handler { @Override protected void handlerRequest(Integer request) { if (request > 100) { System.out.println("HandlerRequest01能处理"); } else if (handler != null) { System.out.println("HandlerRequest01不能处理,交给下一位"); handler.handlerRequest(request);// 由下一位来处理请求 } else if (handler == null) { System.out.println("均不能处理"); } }}public class HandlerRequest02 extends Handler { @Override protected void handlerRequest(Integer request) { if (request > 0 && request < 100) { System.out.println("handlerRequest02能处理"); } else if (handler != null) { System.out.println("handlerRequest02不能处理,交给下一位"); handler.handlerRequest(request);//由下一位来处理请求 } else if (handler == null) { System.out.println("均不能处理"); } }}public class HandlerRequest03 extends Handler { @Override protected void handlerRequest(Integer request) { if (request < 0) { System.out.println("HandlerRequest03能处理"); } else if (handler != null) { System.out.println("handlerRequest03不能处理,交给下一位"); handler.handlerRequest(request);//由下一位来处理请求 } else if (handler == null) { System.out.println("均不能处理"); } }}
测试:
public class TextMain { public static void main(String[] args) { // TODO Auto-generated method stub Handler handler01=new HandlerRequest01(); Handler handler02=new HandlerRequest02(); Handler handler03=new HandlerRequest03(); //设置职责链 handler01.setHandler(handler02); handler02.setHandler(handler03); handler01.handlerRequest(-2); }}
通过设置责任链将请求处理类连成一条链状。
部分摘自《大话设计模式》
阅读全文
0 0
- 职责链设计模式
- 【设计模式】职责链
- 设计模式---职责链
- 职责链设计模式
- 职责链设计模式
- 设计模式---职责链模式
- 设计模式-职责链模式
- 设计模式 职责链模式
- 设计模式- 职责链模式
- 设计模式 - 职责链模式
- 设计模式 - 职责链模式
- 设计模式-职责链模式
- 设计模式--职责链模式
- 设计模式-职责链模式
- 设计模式--职责链模式
- 设计模式-职责链模式
- 【设计模式】职责链模式
- 设计模式-职责链模式
- 消息中间件架构讨论
- maven 环境错误的解决发法
- 手把手教你使用UltraISO软碟通制作win10 Enterprise G企业政府版ISO安装镜像
- 大数据生态系统基础:Apache Kafka基础(三):最新kafka编程入门:Consumer
- 旋转矩阵、欧拉角、四元数比较
- 设计模式--职责链模式
- python错误:UnicodeDecodeError: 'ascii' codec can't decode
- TreeSet使用时注意问题
- CentOS 安装配置LAMP服务器(Apache+PHP5+MySQL)
- 程序员都有一颗摇滚的心
- 实验吧-看起来有点难【基于sleep的sql注入脚本】
- Java 反射在实际开发中的应用
- HMM和CRF简单推导
- 综合---小知识点