Apache commons chain 是什么
Apache common chain 是对责任链设计模式的改造封装,让使用者更加方便的使用。
简单回顾一下责任链设计模式
在阎宏博士的《JAVA与模式》一书中开头是这样描述责任链(Chain of Responsibility)模式的:
责任链模式是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任
关键点:
- 链是一系列节点的集合
- 链的各个节点可随意拆分和组装
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系, 将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理他为止。
责任链适用的场景
-
有多个的对象可以处理一个请求,哪个对象处理该请求运行时刻自动确定。
-
你想在不明确指定接受者的情况下,想过个对象中的一个提交一个请求。
-
可处理一个请求的对象集合应该被动态指定。
简单例子
1abstract class Handler { 2 3 private Handler nextHandler; 4 5 public Handler getNextHandler() { 6 return nextHandler; 7 } 8 9 public void setNextHandler(Handler nextHandler) { 10 this.nextHandler = nextHandler; 11 } 12 13 public abstract void doHandler(); 14 15} 16 17class ConcreteHandler extends Handler { 18 19 @Override 20 public void doHandler() { 21 22 if (getNextHandler() != null) { 23 24 System.out.println("还有责任链"); 25 getNextHandler().doHandler(); 26 } else { 27 28 System.out.println("我自己处理" + toString()); 29 } 30 31 } 32}
设计模式主体架构:
角色:
抽象处理者角色(Handler):定义出一个处理请求的接口。如果需要,接口可以定义 出一个方法以设定和返回对下家的引用。这个角色通常由一个Java抽象类或者Java接口实现。 具体处理者角色(ConcreteHandler):具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。由于具体处理者持有对下家的引用,因此,如果需要,具体处理者可以访问下家。 抽象处理者角色
1public abstract class Handler { 2 3 /** 4 * 持有后继的责任对象 5 */ 6 protected Handler successor; 7 /** 8 * 示意处理请求的方法,虽然这个示意方法是没有传入参数的 9 * 但实际是可以传入参数的,根据具体需要来选择是否传递参数 10 */ 11 public abstract void handleRequest(); 12 /** 13 * 取值方法 14 */ 15 public Handler getSuccessor() { 16 return successor; 17 } 18 /** 19 * 赋值方法,设置后继的责任对象 20 */ 21 public void setSuccessor(Handler successor) { 22 this.successor = successor; 23 } 24 25}
具体处理者角色
1public class ConcreteHandler extends Handler { 2 /** 3 * 处理方法,调用此方法处理请求 4 */ 5 @Override 6 public void handleRequest() { 7 /** 8 * 判断是否有后继的责任对象 9 * 如果有,就转发请求给后继的责任对象 10 * 如果没有,则处理请求 11 */ 12 if(getSuccessor() != null) 13 { 14 System.out.println("放过请求"); 15 getSuccessor().handleRequest(); 16 }else 17 { 18 System.out.println("处理请求"); 19 } 20 } 21 22}
客户端类:
1public class Client { 2 3 public static void main(String[] args) { 4 //组装责任链 5 Handler handler1 = new ConcreteHandler(); 6 Handler handler2 = new ConcreteHandler(); 7 handler1.setSuccessor(handler2); 8 //提交请求 9 handler1.handleRequest(); 10 } 11 12}
Apache CommonsChain
CommonsChain实现了Chain of Responsebility和Command模式,其中的Catalog + 配置文件的方式使得调用方和Command的实现方的耦合度大大的降低,提高了灵活性。
如何使用
简单写了一个实现:
1/** 2 * <p>Test implementation of <code>Chain</code> that exposes the 3 * <code>getCommands()</code> method publicy.</p> 4 */ 5 6public class TestChain extends ChainBase { 7 8 9 /** 10 * 获取责任链中所有加入的命令 11 * @return 责任链中的命令 12 */ 13 public Command[] getCommands() { 14 15 return (commands); 16 17 } 18 public static void main(String[] args) throws Exception { 19 TestChain testChain=new TestChain(); 20 Context context=new ContextBase(); 21 /** 22 * 加入执行命令1 23 */ 24 testChain.addCommand(new Command() { 25 public boolean execute(Context context) throws Exception { 26 System.out.println("执行命令1"); 27 return false; 28 } 29 }); 30 /** 31 * 加入执行命令2 32 * 注意:返回值为true 表示执行到此为止 33 */ 34 testChain.addCommand(new Command() { 35 public boolean execute(Context context) throws Exception { 36 System.out.println("执行命令2"); 37 return true; 38 } 39 }); 40 /** 41 * 加入执行命令3 42 */ 43 testChain.addCommand(new Command() { 44 public boolean execute(Context context) throws Exception { 45 System.out.println("执行命令3"); 46 return false; 47 } 48 }); 49 //执行链中的命令 50 testChain.execute(context); 51 //打印链中的所有命令 52 Command[] commands=testChain.getCommands(); 53 for(Command command:commands){ 54 System.out.println(command.getClass()); 55 } 56 } 57 58}
** 执行结果 **
1- 执行命令1 2- 执行命令2 3- class org.apache.commons.chain.config.TestChain$1 4- class org.apache.commons.chain.config.TestChain$2 5- class org.apache.commons.chain.config.TestChain$3
基本对象
-
1. Command接口。它是Commons Chain中最重要的接口,表示在Chain中的具体某一步要执行的命令。它只有一个方法:boolean execute(Context context)。如果返回true,那么表示Chain的处理结束,Chain中的其他命令不会被调用;返回false,则Chain会继续调用下一个Command,直到:
-
[x] > Command返回true;
-
[x] > Command抛出异常;
-
[x] > Chain的末尾;
-
2. Context接口。它表示命令执行的上下文,在命令间实现共享信息的传递。Context接口的父接口是Map,ContextBase实现了Context。对于web环境,可以使用WebContext类及其子类(FacesWebContext、PortletWebContext和ServletWebContext)。
-
3. Chain接口。它表示“命令链”,要在其中执行的命令,需要先添加到Chain中。Chain的父接口是Command,ChainBase实现了它。
使用配置文件
1test-config.xml 2<catalog> 3 <chain name="Execute"> 4 <command id="1" 5 className="org.apache.commons.chain.impl.DelegatingCommand"/> 6 <command id="2" 7 className="org.apache.commons.chain.impl.DelegatingCommand"/> 8 <command id="3" 9 className="org.apache.commons.chain.impl.ExceptionCommand"/> 10 </chain> 11</catalog>
装入配置文件
1public class ConfigParserTestCase extends TestCase { 2 3 4 private static final String DEFAULT_XML = 5 "/org/apache/commons/chain/config/test-config.xml"; 6 // ------------------------------------------------------------ Constructors 7 /** 8 * Construct a new instance of this test case. 9 * 10 * @param name Name of the test case 11 */ 12 public ConfigParserTestCase(String name) { 13 super(name); 14 } 15 // ------------------------------------------------------ Instance Variables 16 /** 17 * <p>The <code>Catalog</code> to contain our configured commands.</p> 18 */ 19 protected Catalog catalog = null; 20 /** 21 * <p>The <code>Context</code> to use for execution tests.</p> 22 */ 23 protected Context context = null; 24 /** 25 * <p>The <code>ConfigParser</code> instance under test.</p> 26 */ 27 protected ConfigParser parser = null; 28 // ---------------------------------------------------- Overall Test Methods 29 /** 30 * Set up instance variables required by this test case. 31 */ 32 public void setUp() { 33 catalog = new CatalogBase(); 34 context = new ContextBase(); 35 parser = new ConfigParser(); 36 } 37 /** 38 * Return the tests included in this test suite. 39 */ 40 public static Test suite() { 41 return (new TestSuite(ConfigParserTestCase.class)); 42 } 43 /** 44 * Tear down instance variables required by this test case. 45 */ 46 public void tearDown() { 47 parser = null; 48 context = null; 49 catalog = null; 50 } 51 /** 52 执行测试方法 53 **/ 54 public void testExecute2c() throws Exception { 55 56 load(DEFAULT_XML); 57 try { 58 catalog.getCommand("Execute").execute(context); 59 } catch (ArithmeticException e) { 60 assertEquals("Correct exception id", 61 "3", e.getMessage()); 62 } 63 checkExecuteLog("1/2/3"); 64 } 65 /** 66 从配置文件中加载配置信息 67 **/ 68 protected void load(String path) throws Exception { 69 parser.parse(this.getClass().getResource(path)); 70 catalog = CatalogFactoryBase.getInstance().getCatalog(); 71 } 72 73 74} 75
注意:使用配置文件的话,需要使用Commons Digester。而Digester则依赖:Commons Collections、Commons Logging和Commons BeanUtils。
-
4. Filter接口。它的父接口是Command,它是一种特殊的Command。除了Command的execute,它还包括一个方法:boolean postprocess(Context context, Exception exception)。Commons Chain会在执行了Filter的execute方法之后,执行postprocess(不论Chain以何种方式结束)。Filter的执行execute的顺序与Filter出现在Chain中出现的位置一致,但是执行postprocess顺序与之相反。如:如果连续定义了filter1和filter2,那么execute的执行顺序是:filter1 -> filter2;而postprocess的执行顺序是:filter2 -> filter1。
-
5. Catalog接口。它是逻辑命名的Chain和Command集合。通过使用它,Command的调用者不需要了解具体实现Command的类名,只需要通过名字就可以获取所需要的Command实例。
-
6.<define>的使用。配置文件的引入,使得Commons Chain的灵活性大大的提高。在实际的使用过程中,存在着同一个Command被多个Chain使用的情形。如果每次都书写Command的类名,尤其是前面的包名特别长的情况下,是非常枯燥的。而<define>的作用就是为了解决这样的麻烦。通过定义Command和Chain的别名,来简化书写。配置文件,可以书写成:
<?xml version="1.0" encoding="gb2312"?> <catalog> <!-- Command的别名,以后直接使用即可 --> <define name="command1" className="chain.Command1"/> <define name="command2" className="chain.Command2"/> <define name="command3" className="chain.Command3"/> <define name="filter1" className="chain.Filter1"/> <define name="lookupCommand" className="org.apache.commons.chain.generic.LookupCommand"/>
</catalog>1 <chain name="CommandChain"> 2 <command1 id="1"/> 3 <filter1 id="2"/> 4 <lookupCommand name="chain_command3" optional="true"/> 5 <command2 id="3"/> 6 </chain> 7 8 <chain name="chain_command3"> 9 <command3 id="3"/> 10 </chain> 11 12 <command1 name="command4"/>
参考: