設計模式——責任鏈模式
阿新 • • 發佈:2018-03-31
IT ger bst student AR down OS 分享圖片 我們
背景:
想必獎學金大家都不陌生,在學校裏獎學金往往分為三種班獎學金、院級獎學金以及校級獎學金,但是我們往往苦於政策修改,不知道自己的獎學金該找誰領,於是乎就詢問順序就是:班級輔導員->學院老師->學校老師,我們最多且只能在一個人那到一份獎學金,這就是職責鏈。輔導員處領不到就輔導員就會讓你問問學院老師,學院老師處領不到就會讓你問問學校老師,這互相(推脫)其實就是職責鏈模式。
責任鏈模式圖:
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異常困難
使用場景,在字符類型判斷需求中就可以使用該設計模式
設計模式——責任鏈模式