示例代码
抽象批准者
- 责任链的链式结构抽象在这个角色中;
- Approver 包含了自身的引用 approver,当approver被赋值了之后,就形成了链式结构了;
- 责任链的构建是在客户端构建的;
public abstract class Approver {
protected Approver approver;
public void setNextApprover(Approver approver){
this.approver = approver;
}
public abstract void deploy(Course course);
}
具体批准者
- 实现了具体的批准方法;
- 在批准方法中有一个重点:看责任链是不是还有下一个批准者,如果有的话,将任务交由下一个批准者执行;
public class ArticleApprover extends Approver {
@Override
public void deploy(Course course) {
if(StringUtils.isNotEmpty(course.getArticle())){
System.out.println(course.getName()
+ "含有手记,批准");
if(approver != null){
approver.deploy(course);
}
}else{
System.out.println(course.getName()
+ "不含有手记,不批准,流程结束");
return;
}
}
}
public class VideoApprover extends Approver{
@Override
public void deploy(Course course) {
if(StringUtils.isNotEmpty(course.getVideo())){
System.out.println(course.getName()
+ "含有视频,批准");
if(approver != null){
approver.deploy(course);
}
}else{
System.out.println(course.getName()
+ "不含有视频,不批准,流程结束");
return;
}
}
}
责任链处理的对象(请求)
- 这个对象会在责任链中传递;
public class Course {
private String name;
private String article;
private String video;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
@Override
public String toString() {
return "Course{" +
"name='" + name + '\'' +
", article='" + article + '\'' +
", video='" + video + '\'' +
'}';
}
}
客户端
- 责任链的构建是在客户端构建完成的;
public class Test {
public static void main(String[] args) {
Approver articleApprover = new ArticleApprover();
Approver videoApprover = new VideoApprover();
Course course = new Course();
course.setName("Java设计模式精讲 -- By Geely");
course.setArticle("Java设计模式精讲的手记");
course.setVideo("Java设计模式精讲的视频");
articleApprover.setNextApprover(videoApprover);
articleApprover.deploy(course);
}
}
输出:
Java设计模式精讲 -- By Geely含有手记,批准
Java设计模式精讲 -- By Geely含有视频,批准