Press "Enter" to skip to content

设计模式—职责链(Chain of Responsibility)

如果你有Web方面的经验,在JavaScript中的事件流、Java Web中的过滤器,其实都是职责链模式的体现。



package DesignPattern;

public class Chain {
    public static void main(String[] args) {
        Solver C = new ConcreteSolver(null,"C");
        Solver B = new ConcreteSolver(C,"B");
        Solver A = new ConcreteSolver(B,"A");
        Question q = new Question("C");
        A.solve(new Question("B"));

class Question {
    String type; //问题类型
    Question(String t) {
        type = t;

abstract class Solver {
    Solver next; //next用于保存职责链中的下一个成员
    String myType; //myType用于保存当前Solver可解决的问题类型
    abstract void solve(Question q);

class ConcreteSolver extends Solver {
    ConcreteSolver(Solver next,String t) { = next;
        this.myType = t;

    void solve(Question q) {
        if (q.type.equals(this.myType)) {
            System.out.println("my type is " + this.myType + ", I have solved " + q.type);
        }else {
            System.out.println("my type is " + this.myType + ", I can't solve " + q.type);
            if (next != null) next.solve(q);

my type is A, I can't solve C
my type is B, I can't solve C
my type is C, I have solved C
my type is A, I can't solve B
my type is B, I have solved B


Be First to Comment


电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see