概念
使多個對象都有機會處理請求,從而避免請求的發送者和接收者之間的耦合關係,將這個對象連成一條鏈,並沿着這條鏈傳遞該請求,直到有一個對象處理它爲止。
抽象對象負責設定職責鏈的下一級,具體的執行方法在子類裏重寫。
代碼
抽象角色
public abstract class Student {
public Student higherStudent;
public abstract void answer(String question);
public void setHigherStudent(Student higherStudent){
this.higherStudent = higherStudent;
}
}
具體角色A
public class SmallSchoolStudent extends Student{
@Override
public void answer(String question) {
if ("小學生的問題".equals(question)) {
System.out.println("一個小學生回答了這個問題");
} else {
higherStudent.answer(question);
}
}
}
具體角色B
public class MediumSchoolStudent extends Student {
@Override
public void answer(String question) {
if ("中學生的問題".equals(question)) {
System.out.println("一箇中學生回答了這個問題");
} else {
higherStudent.answer(question);
}
}
}
具體角色C
public class CollegeSchoolStudent extends Student {
@Override
public void answer(String question) {
if ("大學生的問題".equals(question)) {
System.out.println("一個大學生回答了這個問題");
} else {
System.out.println("沒有學生能回答這個問題");
}
}
}
客戶端
public class Client {
public static void main(String[] args) {
SmallSchoolStudent smallSchoolStudent = new SmallSchoolStudent();
MediumSchoolStudent mediumSchoolStudent = new MediumSchoolStudent();
CollegeSchoolStudent collegeSchoolStudent = new CollegeSchoolStudent();
smallSchoolStudent.setHigherStudent(mediumSchoolStudent);
mediumSchoolStudent.setHigherStudent(collegeSchoolStudent);
smallSchoolStudent.answer("小學生的問題");
smallSchoolStudent.answer("中學生的問題");
smallSchoolStudent.answer("大學生的問題");
smallSchoolStudent.answer("超難的問題");
//
}
}
特點
職責鏈模式可以實現發送者與處理者的解耦,同時修改下一級別的對象可以實現對職責鏈的動態修改。但是使用職責鏈模式需要保證職責鏈的完整,以及職責鏈的末端需要處理。