概念:
- 为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
- 在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
代码实现:
目录结构:
具体代码:
接口:
package service;
/**
* @author SHshuo
* @data 2021/11/1--18:47
*/
public interface Handler {
default void execute(ChainHandler handler){
// 调用自己的方法
handlerproceed();
// 循环回来调用ChainHandler链表的方法
handler.proceed();
}
void handlerproceed();
}
package service.Impl;
import service.Handler;
/**
* @author SHshuo
* @data 2021/11/1--18:47
*/
public class HanderASubject implements Handler {
@Override
public void handlerproceed() {
System.out.println("HanderASubject");
}
}
package service;
import java.util.List;
/**
* @author SHshuo
* @data 2021/11/1--18:49
* 链
*/
public class ChainHandler {
private List<Handler> handlers;
// 定义游标
private int index = 0;
public ChainHandler(List<Handler> handlers){
this.handlers = handlers;
}
public void proceed(){
if(index >= handlers.size()){
return;
}
// 调用Handler的方法、循环起来了
handlers.get(index++).execute(this);
}
}
package controller;
import service.ChainHandler;
import service.Handler;
import service.Impl.HanderASubject;
import service.Impl.HanderBSubject;
import service.Impl.HanderCSubject;
import java.util.Arrays;
import java.util.List;
/**
* @author SHshuo
* @data 2021/11/1--18:46
* 责任链模式
*/
public class ClientController {
public static void main(String[] args) {
List<Handler> handlers = Arrays.asList(
new HanderASubject(),
new HanderBSubject(),
new HanderCSubject()
);
ChainHandler chainHandler = new ChainHandler(handlers);
chainHandler.proceed();
}
}
UML类图
补充:
spring使用ReflectiveMethodInvocation.java实现责任链模式,从而实现链式调用。

京公网安备 11010502036488号