责任链

包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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值