职责链模式-大话设计模式

简介: 职责链模式-大话设计模式

一、介绍

职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

接收者和发送者都没有对方的明确信息,且链中的对象自己也并不知道链的结构。结果是职责链可简化对象的相互连接,它们仅需保持一个指向其后继者的引用,而不需保持它所有的候选接受者的引用。


随时地增加或修改处理一个请求的结构。增强了给对象指派职责的灵活性。

二、代码实现

public abstract class Handler {
    //继任者
    protected  Handler successor;
    //设置继任者
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    public abstract void handleRequest(int request);
}
 
public class ConcreteHandler1 extends Handler {
    @Override
    public void handleRequest(int request) {
        if (request >= 0 && request < 10) {
            System.out.println(this.getClass().getSimpleName() + "处理请求:" + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        } else {
            throw new RuntimeException("error");
        }
    }
}
 
 
public class ConcreteHandler2 extends Handler {
    @Override
    public void handleRequest(int request) {
        if (request >= 10 && request < 20) {
            System.out.println(this.getClass().getSimpleName() + "处理请求:" + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        } else {
            throw new RuntimeException("error");
        }
    }
}
 
public class ConcreteHandler3 extends Handler {
    @Override
    public void handleRequest(int request) {
        if (request >= 20 && request < 30) {
            System.out.println(this.getClass().getSimpleName() + "处理请求:" + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        } else {
            throw new RuntimeException("error");
        }
    }
}

测试

public class Client {
    public static void main(String[] args) {
        Handler h1 = new ConcreteHandler1();
        Handler h2 = new ConcreteHandler2();
        Handler h3 = new ConcreteHandler2();
        h1.setSuccessor(h2);
        h2.setSuccessor(h3);
        int[] requests = {2, 10, 9, 15, 55, 21};
        for (int request : requests) {
            h1.handleRequest(request);
        }
 
    }
}

目录
相关文章
|
2月前
|
设计模式
二十三种设计模式全面解析-职责链模式的高级应用-日志记录系统
二十三种设计模式全面解析-职责链模式的高级应用-日志记录系统
|
2月前
|
设计模式
二十三种设计模式:解密职责链模式-购物优惠活动的设计艺术
二十三种设计模式:解密职责链模式-购物优惠活动的设计艺术
|
10天前
|
设计模式
行为设计模式之职责链模式
行为设计模式之职责链模式
|
2月前
|
设计模式 Go
[设计模式 Go实现] 行为型~职责链模式
[设计模式 Go实现] 行为型~职责链模式
|
2月前
|
设计模式 Java
小谈设计模式(25)—职责链模式
小谈设计模式(25)—职责链模式
|
9月前
|
设计模式 缓存 Java
行为型设计模式08-职责链模式
行为型设计模式08-职责链模式
27 0
|
2月前
|
设计模式 JavaScript
职责链模式--设计模式
职责链模式--设计模式
9 0
|
12月前
|
设计模式
设计模式——职责链模式
设计模式——职责链模式
|
12月前
|
设计模式 JavaScript 前端开发
|
2月前
|
设计模式
二十三种设计模式全面解析-解密职责链模式:请求处理的设计艺术
二十三种设计模式全面解析-解密职责链模式:请求处理的设计艺术