前一篇 文章,我们大概介绍了 Apache commons chain 及完成了一个简单的demo ,今天我们就从 源码级别来分析下,到底是一个什么样的执行流程 ~~~~!
首先从执行入口类:
public class CommondChain extends ChainBase {
public CommondChain() {
super();
addCommand(new GetUserInfo());
addCommand(new TestDriver());
addCommand(new NegotiateSale());
addCommand(new ArrangeFinancing());
addCommand(new CloseSale());
}
public static void main(String[] args) {
CommondChain commondChain = new CommondChain();
Context context = new ContextBase();
try {
commondChain.execute(context);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我们从两个方面来进行源码解析:
1、实现了Command 的业务功能如何加入容器中?加入到什么容器中?
具体实现 在 ChainBase.class
public void addCommand(Command command) {
if (command == null) {
throw new IllegalArgumentException();
}
if (frozen) {
throw new IllegalStateException();
}
Command[] results = new Command[commands.length + 1];
System.arraycopy(commands, 0, results, 0, commands.length);
results[commands.length] = command;
commands = results;
}
其中,commands 为数组类型。说白了就是加入一个业务处理command 就追加到数组里面去。
如何执行这个流程呢?
具体调用也是在 ChainBase.class
public boolean execute(Context context) throws Exception {
// Verify our parameters
if (context == null) {
throw new IllegalArgumentException();
}
// Freeze the configuration of the command list
frozen = true;
// Execute the commands in this list until one returns true
// or throws an exception
boolean saveResult = false;
Exception saveException = null;
int i = 0;
int n = commands.length;
for (i = 0; i < n; i++) {
try {
saveResult = commands[i].execute(context);
if (saveResult) {
break;
}
} catch (Exception e) {
saveException = e;
break;
}
}
// Call postprocess methods on Filters in reverse order
if (i >= n) { // Fell off the end of the chain
i--;
}
boolean handled = false;
boolean result = false;
for (int j = i; j >= 0; j--) {
if (commands[j] instanceof Filter) {
try {
result =
((Filter) commands[j]).postprocess(context,
saveException);
if (result) {
handled = true;
}
} catch (Exception e) {
// Silently ignore
}
}
}
// Return the exception or result state from the last execute()
if ((saveException != null) && !handled) {
throw saveException;
} else {
return (saveResult);
}
}
看下 代码实现思路还是很简单的哈~~
- 定义一个基类
- 业务逻辑分别实现该基类
- 迭代该数组集合类
- 调用业务类实现方法,完成顺序一个执行流程
Filter 部分代码逻辑,同理,自行去分析看下了~~~
----------------------研究源码最好的方式就是 Debug
网友评论