责任链设计模式是一种行为模式,其中一组对象按顺序连接在一起,请求在对象链上传递,直到有一个对象处理该请求,返回一个响应对象。否则该请求将继续往下传递。
什么是责任链模式
为了更好的理解该责任链模式,举一个现实生活中的例子。假设你手中有一个难题,首先你会尝试自己去解决,如果自己无法解决,你会告诉你的一个朋友请求他解决,如果他也无法解决,则他会将该问题传递给下一个朋友去解决,直到有一个人解决了该难题,或者没有人解决。
责任链模式的意图是避免将请求的发送者和接收者耦合在一起,让每一个接收者都有机会处理该请求。将接收者按顺序连接在一起,并将请求在这条链上往下传递,直到有一个对象处理了该请求。

Handler
处理请求的接口
ConcreteHandler
处理请求的对象
Client
初始化请求并将请求传递到Handler对象链
实现
Handler表示处理请求对象
| 12
 3
 4
 5
 6
 7
 
 | public interface Handler {
 void process(File file);
 
 String name();
 
 }
 
 | 
TextFileHandler可以处理文本类文件
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | 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可以处理图像类文件
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | 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表示被处理的请求
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | 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";
 }
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | 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处理。