行为型模式之六:责任链模式

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

责任链类图

责任链的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);
  }
}

输出less

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

在这个例子中,Leve1 经过了链中因此单元。 这是wiki中例子的简化: http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern 责任链在Java JDK中使用 (PS:原文中没有下方了,可是Java中类加载器就是使用了责任链模式)ui

相关文章
相关标签/搜索