责任链模式

定义

为请求创建一个接收此次请求对象的链;
行为型

适用场景

  • 一个请求的处理需要多个对象当中的一个或几个协同处理;

优点和缺点

优点

  • 请求的发送者和接收者(请求的处理)解耦
  • 责任链可以动态组合

缺点

  • 责任链太长或者处理时间过长,影响性能;
  • 责任链有可能过多。

结构

  • 抽象处理者角色:定义一个处理请求的接口,包含抽象处理方法和一个后续连接。
  • 具体处理者角色:实现抽象处理者的处理方法,判断能否处理本次请求,如果可以处理请求则处理,否则将该请求转给它的后继者。
  • 客户类角色:创建处理链,并向链头的具体处理对象提交请求,它不关心处理细节和请求的传递过程。

代码实现

假设我们有一个文档,需要审核标题和内容,先审核标题,后审核内容,标题不合格直接结束
文档实体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Word {

private String title;
private String content;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}
}

抽象处理者角色:
里面保存了下一级审核的对象指向,以及审核的具体逻辑实现方法

1
2
3
4
5
6
7
8
9
10
public abstract class Handler {

protected Handler handler;

public void setNext(Handler handler) {
this.handler = handler;
}

abstract void examine(Word word);
}

具体处理者角色:
标题审核,如果通过进行下一步审核,如果不通过,直接结束

1
2
3
4
5
6
7
8
9
10
11
12
13
public class TitleHandler extends Handler{
@Override
void examine(Word word) {
if (word.getTitle() != null && !"".equals(word.getTitle())){
System.out.println("标题合格,通用审核");
if (handler != null){
handler.examine(word);
}
}else {
System.out.println("标题不合格,不通过审核");
}
}
}

具体处理者角色:
内容审核,如果通过进行下一步,如果不通过,结束

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ContentHandler extends Handler{
@Override
void examine(Word word) {
if (word.getContent() != null && !"".equals(word.getContent())){
System.out.println("内容合格,通用审核");
if (handler != null){
handler.examine(word);
}
}else {
System.out.println("内容不合格,不通过审核");
}
}
}

客户角色类:
组装具体的责任链,设置审核先后层级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test {

public static void main(String[] args) {
TitleHandler titleHandler = new TitleHandler();
ContentHandler contentHandler = new ContentHandler();
titleHandler.setNext(contentHandler);

Word word = new Word();
word.setTitle("责任链模式");
// word.setContent("责任链模式内容");

titleHandler.examine(word);
}

}

结果:

1
2
标题合格,通用审核
内容不合格,不通过审核

UML类图