责任链模式是行为模式的一种
责任链模式 :当处理户端发起的一个请求时,通过一串对象来处理他们,而达到的一种松耦合软件设计的目的
对请求有责任处理的多个类组成的链,如请假审批流程、采购审批流程。
- 当代码由很多个if else时,可以用责任链重构
- 请求处理方法在后续的需求大概率会新增时
优点
解耦 请求和请求处理分开
单一职责 每个处理类只需关心自己的业务,不需要知道下个处理是谁
符合开闭原则 新增处理方法简单
缺点
多个链路处理效率不高,单个处理会影响整体速度。
会存在无效遍历,空循环
容易写成死循环
举个栗子 过滤诗歌 1去除空格 2格式化 3提取名句
上代码
public abstract class Handle {
protected Handle next;
public void next(Handle next){
this.next = next;
}
public abstract void handle(Poetry poetry);
}
public class SpaceHandle extends Handle {
@Override
public void handle(Poetry poetry) {
System.out.println("---------去除空格--------------");
String content = poetry.getContent().replace(" ", "");
poetry.setContent(content);
System.out.println(content);
next.handle(poetry);
}
}
public class FormatHandle extends Handle {
@Override
public void handle(Poetry poetry) {
System.out.println("---------格式化--------------");
String content = poetry.getContent();
String[] a = content.split("。");
System.out.println(" "+poetry.getTitle());
System.out.println(" "+poetry.getAuthor());
Arrays.stream(a).forEach(b->{
System.out.print(b);
System.out.println("。");
});
this.next.handle(poetry);
}
}
public class FamousSentenceHandle extends Handle {
@Override
public void handle(Poetry poetry) {
System.out.println("---------名句提取--------------");
String content = poetry.getContent();
String[] cons = content.split("。");
String famous = cons[1].toString();
System.out.println();
System.out.println(famous);
}
}
@Data
public class Poetry {
Poetry(String author,String content,String title){
this.author = author;
this.content = content;
this.title = title;
}
String author;
String content;
String title;
}
测试类
public class Test {
public static void main(String[] args) {
Poetry poetry = new Poetry("陆游", " 莫笑农家腊酒浑,丰年留客足鸡豚。 山重水复疑无路,柳暗花明又一村。箫鼓追随春社近, 衣冠简朴古风存。从今若许闲乘月,拄杖无时夜叩门。", "游山西村");
SpaceHandle spaceHandle = new SpaceHandle();
FormatHandle formatHandle = new FormatHandle();
FamousSentenceHandle famousSentenceHandle = new FamousSentenceHandle();
spaceHandle.next(formatHandle);
formatHandle.next(famousSentenceHandle);
System.out.println("---------原句--------------");
System.out.println(poetry.getContent());
spaceHandle.handle(poetry);
}
}
执行结果