责任链的描述是:当你想要让一个已上的对象有机会能够处理某个请求的时候,就是使用它。这个模式也挺常用的,比如说Netty中处理各种Handler的Pipline。
场景描述
假设现在要实现一个邮件过滤的功能,将收到的邮件发送给各个过滤器依次执行,下面看下责任链模式如何实现。
创建Mail类,不需要实际功能,空着就可以了
12public class Mail {}创建Handler抽象类,所有的Handler都继承该抽象类
1234567891011121314151617181920public abstract class MailHandler {/*** 下一个Handler*/protected MailHandler next;public MailHandler(MailHandler next) {this.next = next;}public void toNext(Mail mail) {if (next != null) {next.handler(mail);} else {System.out.println("Chain handler end.");}}public abstract void handler(Mail mail);}实现各个Handler子类
1234567891011public class SpamHandler extends MailHandler {public SpamHandler(MailHandler next) {super(next);}public void handler(Mail mail) {System.out.println("Spam handler processing");toNext(mail);}}1234567891011public class FanHandler extends MailHandler {public FanHandler(MailHandler next) {super(next);}public void handler(Mail mail) {System.out.println("Fan handler processing");toNext(mail);}}1234567891011public class ComplainHandler extends MailHandler {public ComplainHandler(MailHandler next) {super(next);}public void handler(Mail mail) {System.out.println("Complain handler processing");toNext(mail);}}1234567891011public class NewLocHandler extends MailHandler {public NewLocHandler(MailHandler next) {super(next);}public void handler(Mail mail) {System.out.println("New loc handler processing");toNext(mail);}}测试
123456789101112public class Test {public static void main(String[] args) {MailHandler mailHandler = new SpamHandler(new FanHandler(new ComplainHandler(new NewLocHandler(null))));mailHandler.handler(new Mail());}}
责任链模式的简单演示就结束了,这个模式看起来也不复杂,有点像链表结构,各个Handler有下一个Handler的引用。本章节就到这里了。