设计模式():职责链模式

概念

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
抽象对象负责设定职责链的下一级,具体的执行方法在子类里重写。

代码

抽象角色

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("超难的问题");
//

    }
}

特点

职责链模式可以实现发送者与处理者的解耦,同时修改下一级别的对象可以实现对职责链的动态修改。但是使用职责链模式需要保证职责链的完整,以及职责链的末端需要处理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章