博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
行为型模式之六:责任链模式
阅读量:6946 次
发布时间:2019-06-27

本文共 1857 字,大约阅读时间需要 6 分钟。

  hot3.png

责任链的主要意图是创建一个处理单元链,当每个单元满足阀值后都处理请求。当链建立之后,如果一个单元没有满足,就会尝试下一个单元,依次下去,每个请求都会单独通过链。

责任链类图

责任链的Java代码

package designpatterns.cor; abstract class Chain {  public static int One = 1;  public static int Two = 2;  public static int Three = 3;  protected int Threshold;   protected Chain next;   public void setNext(Chain chain) {    next = chain;  }   public void message(String msg, int priority) {    //if the priority is less than Threshold it is handled  	if (priority <= Threshold) {      writeMessage(msg);    }     if (next != null) {      next.message(msg, priority);    }  }   abstract protected void writeMessage(String msg);} class A extends Chain {  public A(int threshold) {     this.Threshold = threshold;  }   protected void writeMessage(String msg) {    System.out.println("A: " + msg);  }}  class B extends Chain {  public B(int threshold) {     this.Threshold = threshold;  }   protected void writeMessage(String msg) {    System.out.println("B: " + msg);  }} class C extends Chain {  public C(int threshold) {     this.Threshold = threshold;  }   protected void writeMessage(String msg) {    System.out.println("C: " + msg);  }}  public class ChainOfResponsibilityExample {   private static Chain createChain() {    // Build the chain of responsibility   	Chain chain1 = new A(Chain.Three);   	Chain chain2 = new B(Chain.Two);  	chain1.setNext(chain2);     Chain chain3 = new C(Chain.One);        chain2.setNext(chain3);     return chain1;  }   public static void main(String[] args) {   	Chain chain = createChain();     chain.message("level 3", Chain.Three);     chain.message("level 2", Chain.Two);     chain.message("level 1", Chain.One);  }}

输出

A: level 3A: level 2B: level 2A: level 1B: level 1C: level 1

在这个例子中,Leve1 通过了链中所以单元。 这是wiki中例子的简化: 责任链在Java JDK中使用 (PS:原文中没有下方了,但是Java中类加载器就是使用了责任链模式)

转载于:https://my.oschina.net/markho/blog/498245

你可能感兴趣的文章
Unity HoloLens开发配置
查看>>
vim剪贴板小结
查看>>
Thinkpad ACCESS CONNECTIONS异常解决
查看>>
各行业对邮件服务器需求及解决方案
查看>>
linux软件管理与使用
查看>>
qt 使用样式设置渐变色背景
查看>>
ubuntu16.04 安装 操作 redis
查看>>
IIS启动网站出错的几个解决方法
查看>>
mysql对vachar排序的问题
查看>>
ASCII和Unicode编码
查看>>
什么事宏病毒,宏病毒的判断方法 ,宏病毒的防治和清除
查看>>
实战CGLib系列之proxy篇(五):接口生成器InterfaceMaker
查看>>
算法题!大家可以贡献答案哦!
查看>>
此文是2013年应届生实习时,集中培训班的最后,个人写给大家的话
查看>>
JVM致命错误日志(hs_err_pid.log)解读
查看>>
一个老司机工程师整理的自动化测试资料
查看>>
单机环境搭建Postgres-XC开发测试环境
查看>>
三: 推荐系统
查看>>
PHP文件上传-单文件上传函数
查看>>
jvmtop 监控
查看>>