Chain of Responsibility模式
What
"Chain of Responsibility":责任推卸
Chain of Responsibility模式是一种为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止的设计模式
Why
适用场景
当请求和处理者之间的关系是不确定的,而且对处理速度没有太高的要求时,可以使用Chain of Responsibility模式
优点
弱化了发出请求的人和处理请求的人之间的关系
可以动态的改变职责链
专注于自己的工作
How
定义一个抽象类Handler,内有next和request方法
实现Handler接口以适应不用的处理方法
使用者定义职责链
Handler
public abstract class Support {
private String name;
private Support next;
public Support(String name) {
this.name = name;
}
public Support setNext(Support next) {
this.next = next;
return next;
}
public final void support(Trouble trouble) {
if (resolve(trouble)) {
done(trouble);
} else if (next != null) {
next.support(trouble);
} else {
fail(trouble);
}
}
@Override
public String toString() {
return "Support{" +
"name='" + name + '\'' +
'}';
}
protected abstract boolean resolve(Trouble trouble);
protected void done(Trouble trouble) {
System.out.println(trouble + " is resolved by " + this + ".");
}
protected void fail(Trouble trouble) {
System.out.println(trouble + " cannot be resolved.");
}
}
Main使用者
public class Main {
public static void main(String[] args) {
Support alice = new NoSupport("Alice");
Support bob = new LimitSupport("Bob", 100);
Support charlie = new SpecialSupport("Charlie", 429);
Support diana = new LimitSupport("Diana", 200);
Support elmo = new OddSupport("Elmo");
Support fred = new LimitSupport("Fred", 300);
alice.setNext(bob).setNext(charlie).setNext(diana).setNext(elmo).setNext(fred);
for (int i = 0; i < 500; i += 33) {
alice.support(new Trouble(i));
}
}
}
类图
![](https://i-blog.csdnimg.cn/blog_migrate/9a45fe6f28e0758dea254b8cd74d85c4.png)