背景:
想必奖学金大家都不陌生,在学校里奖学金往往分为三种班奖学金、院级奖学金以及校级奖学金,但是我们往往苦于政策修改,不知道自己的奖学金该找谁领,于是乎就询问顺序就是:班级辅导员->学院老师->学校老师,我们最多且只能在一个人那到一份奖学金,这就是职责链。辅导员处领不到就辅导员就会让你问问学院老师,学院老师处领不到就会让你问问学校老师,这互相(推脱)其实就是职责链模式。
责任链模式图:
public interface IStudent {
int getType();
String getRequest();
}
public class Student implements IStudent {
private int type = 0;
private String request = "";
public Student(int type, String request) {
this.type = type;
this.request = request;
}
public int getType() {
return this.type;
}
public String getRequest() {
return this.request;
}
}
public abstract class Handler {
public static final Integer CLASS_SCHOLARSHIP = 1;
public static final Integer COLLEGE_SCHOLARSHIP = 2;
public static final Integer UNIVERSITY_SCHOLARSHIP = 3;
//责任处理级别
private int level = 0;
//下一位处理者
private Handler nextHandler;
public Handler(int level) {
this.level = level;
}
public void HandleMsg(IStudent student) {
if (student.getType() == this.level) {
}
}
public void setNext(Handler handler) {
this.nextHandler = handler;
}
public abstract void response(IStudent student);
}
public class ClassTeacher extends Handler {
public ClassTeacher() {
super(Handler.CLASS_SCHOLARSHIP);
}
public void response(IStudent student) {
System.out.println(student.getRequest());
System.out.println("班级老师批准!");
}
}
public class CollegeTeacher extends Handler{
public CollegeTeacher() {
super(Handler.COLLEGE_SCHOLARSHIP);
}
public void response(IStudent student) {
System.out.println(student.getRequest());
System.out.println("学院老师批准!");
}
}
public class UniversityTeacher extends Handler {
public UniversityTeacher() {
super(Handler.UNIVERSITY_SCHOLARSHIP);
}
public void response(IStudent student) {
System.out.println(student.getRequest());
System.out.println("学校老师批准!");
}
}
责任链缺点:
(1)性能问题,每个请求都会从链头遍历到链尾
(2)如果责任块过多,会导致debug异常困难
使用场景,在字符类型判断需求中就可以使用该设计模式