我们知道设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。
那么此篇中讲的责任链是个什么样的设计模式呢?下面请看责任链的概念阐述
什么是链
1、链是一系列节点的集合。
2.、链的各节点可灵活拆分再重组。
职责链模式
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,
将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理他为止。
角色
抽象处理者角色(Handler):定义出一个处理请求的接口。如果需要,接口可以定义 出一个方法以设定和返回对下家的引用。这个角色通常由一个Java抽象类或者Java接口实现。
具体处理者角色(ConcreteHandler):具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。由于具体处理者持有对下家的引用,因此,如果需要,具体处理者可以访问下家。
下面是我阅读struts2源码时,仿照strut2 拦截器 写的一种责任链设计模式
package com.test.test.design.chain; public interface Interceptor { public String doInterceptor(Invocation invocation); }
//具体角色一 public class OneInterceptor implements Interceptor{ @Override public String doInterceptor(Invocation invocation) { System.out.println("interceptor one"); invocation.invoke(); return "success "; } } //具体角色二 public class TwoInterceptor implements Interceptor{ @Override public String doInterceptor(Invocation invocation) { System.out.println("interceptor two"); invocation.invoke(); return "success"; } } //具体角色三 public class ThreeInterceptor implements Interceptor { @Override public String doInterceptor(Invocation invocation) { System.out.println("interceptor one"); invocation.invoke(); return null; } }
角色有了 那么缺一个调度者吧,
public interface Invocation { public void invoke(); } public class DefaultInvocation implements Invocation{ Iterator<Interceptor> iterator; public DefaultInvocation(){ List<Interceptor> interceptors=new ArrayList<Interceptor>(); interceptors.add(new OneInterceptor()); interceptors.add(new TwoInterceptor()); interceptors.add(new ThreeInterceptor()); iterator=interceptors.iterator(); } @Override public void invoke(){ System.out.println("DefaultInvocation start....."); String result=null; if(iterator.hasNext()){ result=iterator.next().doInterceptor(this); }else{ System.out.println("action execute...."); } } public void dd(){ } public static void main(String[] args) { Invocation invocation=new DefaultInvocation(); invocation.invoke(); } }
同时上面也包含了我的一段责任链模式的一段测试代码
测试结果如下:
测试结果 写道
DefaultInvocation start.....
interceptor one
DefaultInvocation start.....
interceptor two
DefaultInvocation start.....
interceptor one
DefaultInvocation start.....
action execute....
interceptor one
DefaultInvocation start.....
interceptor two
DefaultInvocation start.....
interceptor one
DefaultInvocation start.....
action execute....
相关推荐
设计模式之职责链模式,这份文档以例子的形式讲诉了设计模式之职责链模式,希望可以帮助需要的人!
在“java设计模式之责任链模式”的主题中,我们可以深入探讨如何在实际项目中应用责任链模式,包括但不限于以下方面: 1. **代码结构优化**:通过责任链模式,可以使代码结构更加清晰,降低类间的耦合度。 2. **可...
责任链模式(Chain of Responsibility)是一种行为设计模式,它允许将请求沿着处理者对象的链进行传递,直到某个对象能够处理这个请求为止。在Java中,我们可以通过接口和类的组合来实现这种模式。让我们深入探讨...
职责链模式(ChainOfResponsibilityPattern)是一种行为设计模式,主要目的是通过建立一个处理请求的对象链,使得请求可以在链上的各个对象间传递,直到被某个对象处理。这种模式可以有效地解耦请求发起者和处理者,...