责任链设计模式是一种行为模式,其中一组对象按顺序连接在一起,请求在对象链上传递,直到有一个对象处理该请求,返回一个响应对象。否则该请求将继续往下传递。
什么是责任链模式
为了更好的理解该责任链模式,举一个现实生活中的例子。假设你手中有一个难题,首先你会尝试自己去解决,如果自己无法解决,你会告诉你的一个朋友请求他解决,如果他也无法解决,则他会将该问题传递给下一个朋友去解决,直到有一个人解决了该难题,或者没有人解决。
责任链模式的意图是避免将请求的发送者和接收者耦合在一起,让每一个接收者都有机会处理该请求。将接收者按顺序连接在一起,并将请求在这条链上往下传递,直到有一个对象处理了该请求。
Handler
处理请求的接口
ConcreteHandler
处理请求的对象
Client
初始化请求并将请求传递到Handler对象链
实现
Handler
表示处理请求对象
public interface Handler {
void process(File file);
String name();
}
复制代码
TextFileHandler
可以处理文本类文件
public class TextFileHandler implements Handler {
private Handler handler;
public TextFileHandler(Handler handler) {
this.handler = handler;
}
@Override
public void process(File file) {
if ("text".equals(file.getType())) {
System.out.println(file.getName() + " was handled by " + name());
} else if (handler != null) {
handler.process(file);
} else {
System.out.println(file.getName() + " is not supported");
}
}
@Override
public String name() {
return "textFileHandler";
}
}
复制代码
ImageFileHandler
可以处理图像类文件
public class ImageFileHandler implements Handler {
private Handler handler;
public ImageFileHandler(Handler handler) {
this.handler = handler;
}
@Override
public void process(File file) {
if ("image".equals(file.getType())) {
System.out.println(file.getName() + " was handled by " + name());
} else if (handler != null) {
handler.process(file);
} else {
System.out.println(file.getName() + " is not supported");
}
}
@Override
public String name() {
return "imageFileHandler";
}
}
复制代码
File
表示被处理的请求
public interface File {
String getName();
String getType();
}
// 图像文件
public class ImageFile implements File {
@Override
public String getName() {
return "imageFile";
}
@Override
public String getType() {
return "image";
}
}
// 文本文件
public class TextFile implements File {
@Override
public String getName() {
return "textFile";
}
@Override
public String getType() {
return "text";
}
}
复制代码
public class Client {
public static void main(String[] args) {
ImageFileHandler imageFileHandler = new ImageFileHandler(null);
TextFileHandler textFileHandler = new TextFileHandler(imageFileHandler);
TextFile textFile = new TextFile();
ImageFile imageFile = new ImageFile();
textFileHandler.process(textFile);
textFileHandler.process(imageFile);
}
}
复制代码
测试程序输出内容
textFile was handled by textFileHandler
textFileHandler could not handle imageFile
imageFile was handled by imageFileHandler
在上述代码中,文件先交由TextFileHandler
处理,若其无法处理则传递到下一个ImageFileHandler
处理。 对于TextFile
,TextFileHandler
直接处理该文件,所以不会再往下传递。 而对于ImageFile
,TextFileHandler
无法处理,则传递到ImageFileHandler
处理。