一碗书小说网

Chain of Responsibility(设计模式之责任链)

责任链: 顾名思义, 就是一条链, 上面有很多个节点,而每个节点承担一种责任,从而构成一条链.

工作流程: 每个节点只负责当前责任,如果超出它所能承担的,就传给下个节点.

public interface Handler {
    public void handleRequest(String request);
}
public class NodeOne implements Handler {

    public void handleRequest(String request) {
        if (request.equals("1")) {
            // We handle help ourselves, so help code is here.
            System.out.println("Node one handle it.");
        }
        else{
            // Pass it on!
            new NodeTwo().handleRequest(request);
        }
    }
}
public class NodeTwo implements Handler {
    
    public void handleRequest(String request) {
        if (request.equals("2")) {
            // We handle help ourselves, so help code is here.
            System.out.println("Node two handle it.");
        }
        else{
            // Pass it on!
            new LastNode().handleRequest(request);
        }
    }
}
public class LastNode implements Handler {
    
    public void handleRequest(String request) {
        if (request.equals("-1")) {
            // We handle help ourselves, so help code is here.
            System.out.println("Last node handle it.");
        }
        else{
            // Pass it on!
            System.out.println("No Node could handle it.");
        }
    }
}
public class Client {
    
    public static void main(String[] args){
        Handler h = new NodeOne();
        h.handleRequest("1");
        h.handleRequest("2");
        h.handleRequest("3");
        h.handleRequest("-1");
    }
    
}

 

>> 怕自己忘记而写的笔记,拿出来分享下~~

 

posted @ 2013-03-10 21:18  艾尔维斯的L  阅读(150)  评论(0编辑  收藏  举报
一碗书小说网