设计模式:责任链模式

责任链模式的主要思想是是建立一个链处理单元,每一个单元如果满足条件都会处理请求。由于是链构建,如果一个单元不满足条件,那么就测试下一个单元等。每一条请求都会沿着链处理。

1、类图



 2、实例代码

package com.leon.chain;

public abstract class Chain {

	public static int One = 1;
	public static int Two = 2;
	public static int Three = 3;

	protected int threshold;
	protected Chain next;

	public void setNext(Chain chain) {
		this.next = chain;
	}

	public void message(String msg, int priority) {
		if (priority <= threshold) {
			writeMessage(msg);
		}

		if (this.next != null) {
			this.next.message(msg, priority);
		}
	}

	abstract void writeMessage(String msg);
}

 

package com.leon.chain;

public class Test {
	public static void main(String[] args) {

		Chain chain = createChain();

		chain.message("level 3", Chain.Three);

		chain.message("level 2", Chain.Two);

		chain.message("level 1", Chain.One);

	}

	public static Chain createChain() {
		Chain chain1 = new A(Chain.Three);

		Chain chain2 = new B(Chain.Two);
		chain1.setNext(chain2);

		Chain chain3 = new C(Chain.One);
		chain2.setNext(chain3);

		return chain1;
	}
}

class A extends Chain {

	public A(int threshold) {
		this.threshold = threshold;
	}

	@Override
	void writeMessage(String msg) {
		// TODO Auto-generated method stub
		System.out.println("A:"+msg);
	}

}

class B extends Chain {

	public B(int threshold) {
		this.threshold = threshold;
	}

	@Override
	void writeMessage(String msg) {
		// TODO Auto-generated method stub
		System.out.println("B:"+msg);
	}

}

class C extends Chain {

	public C(int threshold) {
		this.threshold = threshold;
	}

	@Override
	void writeMessage(String msg) {
		// TODO Auto-generated method stub
		System.out.println("C:"+msg);
	}

}

 在这个例子中,level 1的Message走过了链中所有的单元。

A:level 3
A:level 2
B:level 2
A:level 1
B:level 1
C:level 1

 原文链接:这里

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值