java commons-chain_Apache commons chain简介和简单实现

apache commons chain 提供了对CoR模式的基础支持。。CoR模式,是Chain of Responsebility的缩写。CommonsChain实现了Chain of Responsebility和Command模式,其中的Catalog + 配置文件的方式使得调用方和Command的实现方的耦合度大大的降低,提高了灵活性。

使用Apachecommons chain,需要将commons-chain.jar放入你的classpath,目前最新的版本是1.2。

从使用的角度来看,和工作流(workflow)非常相似。

一个使用Apachecommons chain的简单的例子:

packagetest.ffm83.commons.chain;

importorg.apache.commons.chain.Command;

importorg.apache.commons.chain.Context;

importorg.apache.commons.chain.impl.ChainBase;

importorg.apache.commons.chain.impl.ContextBase;

/**

* 通过commons chain 进行任务链的处理

* @author 范芳铭

*/

publicclass CommandChain  extends ChainBase{

//增加命令的顺序也决定了执行命令的顺序

public CommandChain(){

addCommand( new Command1());

addCommand( new Command2());

addCommand( new Command3());

}

public static void main(String[] args)throws Exception{

CommandChain process = newCommandChain();

Context ctx= new ContextBase();

process.execute( ctx);

}

public class Command1 implements Command {

public boolean execute(Context arg0)throws Exception {

System.out.println("Command1is done!");

return false;

}

}

public class Command2 implements Command {

public boolean execute(Context arg0)throws Exception {

System.out.println("Command2is done!");

return false;

}

}

public class Command3 implements Command {

public boolean execute(Context arg0)throws Exception {

System.out.println("Command3is done!");

return true;

}

}

}

运行结果如下:

Command1is done!

Command2is done!

Command3is done!

使用chain,必须将流程中的每一步写成一个类,这个类需要有一个public的方法execute()。这和传统的命令模式(Command pattern)实现相同。

核心组件和相关概念

1.Context     command的执行的上下文环境,即包含了应用程序的状态。

extends map。继承自map接口,没有增加任何其他的接口方法,它只是一个标记接口。ContextBase是它的实现类。

一般情况下,使用map来记录状态就可以了。例如map.put(state,value),map.get(state).在某些特定的使用时候,若需要明确定义拥有特定状态属性的java bean,例如通过ProfileContext.getXXState()/ProfileContext.setXXState(stateValue)来获得和属性具体的属性值。通过继承ContextBase 来实现,加入特定的属性字段,与此同时获得了两种方式来获取具体的状态。get(state)和getXXState()。通过反射类实现。

2.Command:职责的最小单元。

注意:return false 会继续执行chain中后续的command,return true会停止后续command的执行。

3.filter:是一种特殊的command,加入了postprocess 方法。在chain return之前会去执行postprocess。可以在该方法中释放资源。

4.catalog:command或chain的集合。通过配置文件类加载chain of command 或者command。通过catalog.getCommand(commandName)获取Command。

此外,chain还可以使用XML配置文件的方式使用,能够很方便的注入应用中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值