包commons-chain1.2.jar,责任链描述:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。——引用
代码如下:
public class Test {
public static void main(String[] args) throws Exception {
ContextBase contextBase = new ContextBase();
test1(contextBase);
test2(contextBase);
}
private static void test1(ContextBase contextBase) throws Exception {
ChainBase chain = new ChainBase();
chain.addCommand(new Command1());
chain.addCommand(new Command2());
chain.addCommand(new Command3());
chain.execute(contextBase);
}
private static void test2(ContextBase contextBase) throws Exception {
ChainBase chain2 = new ChainBase();
chain2.addCommand(new Command1());
chain2.addCommand(new Command2());
chain2.addCommand(new Command3());
contextBase.put("user", "liu");
chain2.execute(contextBase);
}
}
public class Command1 implements Command{
@Override
public boolean execute(Context context) throws Exception {
boolean suc = false;
if (context.get("user") == null) {
suc = true;
}
System.out.println("Command1:" + suc);
return suc;
}
}
public class Command2 implements Command {
@Override
public boolean execute(Context context) throws Exception {
boolean suc = false;
if (context.get("user") == null) {
// 这里是false!!!
suc = false;
}
System.out.println("Command2:" + suc);
return suc;
}
}
public class Command3 implements Command {
@Override
public boolean execute(Context context) throws Exception {
boolean suc = false;
if (context.get("user") == null) {
suc = true;
}
System.out.println("Command3:" + suc);
return suc;
}
}
运行结果:
Command1:true
Command1:false
Command2:false
Command3:false