1.定义:为请求创建一个接收此次请求对象的链
2.类型:行为型
3.适用场景:一个请求的处理需要多个对象当中的一个或几个协作处理。
4.优点:请求的发送者和接收者(请求的处理)解耦;责任链可以动态组合。
5.缺点:责任链太长或者处理时间过长,影响性能;责任链有可能过多。
6.相关设计模式:状态模式。
7.实例目录package
8.实例UML类图
9.代码
1 package com.geely.design.pattern.behavioral.chainofresponsibility; 2 3 public class Course { 4 private String name; 5 private String article; 6 private String video; 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 public String getArticle() { 17 return article; 18 } 19 20 public void setArticle(String article) { 21 this.article = article; 22 } 23 24 public String getVideo() { 25 return video; 26 } 27 28 public void setVideo(String video) { 29 this.video = video; 30 } 31 32 @Override 33 public String toString() { 34 return "Course{" + 35 "name='" + name + '\'' + 36 ", article='" + article + '\'' + 37 ", video='" + video + '\'' + 38 '}'; 39 } 40 }
1 package com.geely.design.pattern.behavioral.chainofresponsibility; 2 3 public abstract class Approver { 4 protected Approver approver; 5 6 public void setNextApprover(Approver approver){ 7 this.approver = approver; 8 } 9 public abstract void deploy(Course course); 10 }
1 package com.geely.design.pattern.behavioral.chainofresponsibility; 2 3 import org.apache.commons.lang.StringUtils; 4 5 public class VideoApprover extends Approver { 6 @Override 7 public void deploy(Course course) { 8 if(StringUtils.isNotEmpty(course.getVideo())){ 9 System.out.println(course.getName() + "含有视频,批准"); 10 if(approver != null){ 11 approver.deploy(course); 12 } 13 }else{ 14 System.out.println(course.getName() + "不含有视频,不批准"); 15 return; 16 } 17 } 18 }
1 package com.geely.design.pattern.behavioral.chainofresponsibility; 2 3 import org.apache.commons.lang.StringUtils; 4 5 public class ArticleApprover extends Approver { 6 @Override 7 public void deploy(Course course) { 8 if(StringUtils.isNotEmpty(course.getArticle())){ 9 System.out.println(course.getName() + "含有手记,批准"); 10 if(approver != null){ 11 approver.deploy(course); 12 } 13 }else{ 14 System.out.println(course.getName() + "不含有手记,不批准"); 15 return; 16 } 17 } 18 }
1 package com.geely.design.pattern.behavioral.chainofresponsibility; 2 3 public class Test { 4 public static void main(String[] args) { 5 Approver articleApprover = new ArticleApprover(); 6 Approver videoApprover = new VideoApprover(); 7 Course course = new Course(); 8 course.setName("Java设计模式精讲 -- By Geely"); 9 course.setArticle("Java设计模式精讲的手记"); 10 course.setVideo("Java设计模式精讲的视频"); 11 12 articleApprover.setNextApprover(videoApprover); 13 articleApprover.deploy(course); 14 } 15 }