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

如果你有Web方面的经验,在JavaScript中的事件流、Java Web中的过滤器,其实都是职责链模式的体现。
职责链模式可以这么来形容。A、B、C三个人去参加一个解题比赛,但是A更擅长数学问题,B更擅长理化问题,C更擅长文史问题。于是他们决定这样做:每接到一道题,A先阅读,如果是数学题A解答,否则传给B;B阅读后如果发现是理化题,则B解答,否则传给C来解答。这样A->B->C就构成了一个职责链。

示例代码如下:

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(q);
        System.out.println("----------------");
        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) {
        this.next = 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);
        }
    }
}

/*
output:
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
*/

其实职责链细分还有纯职责链和不纯的职责链,个人感觉根据实际情况自己改造即可,不必分的那么详细。

你可能感兴趣的:(杂乱的东西,设计模式,职责链)