责任链模式

介绍

  GoF 23种设计模式之一。

定义

  避免请求的发送者与接收者耦合在一起,使得多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。

举例

抽象处理接口
abstract class PriceHandler {
	/*
	 * 下一个对象
	 */
	protected PriceHandler next;
	public void setNext(PriceHandler next) {
		this.next = next;
	}
	/*
	 * 折扣
	 */
	public abstract void processDiscount(float discount);

}
具体处理对象
class Sale extends PriceHandler {
	
	public void processDiscount(float discount) {
		if(discount <= 0.2) {
			System.out.format("%s批准了折扣:%.2f%n", this.getClass().getSimpleName(), discount);
		} else {
			next.processDiscount(discount);
		}
	}

}
具体处理对象
class Leader extends PriceHandler {
	
	public void processDiscount(float discount) {
		if(discount <= 0.5) {
			System.out.format("%s批准了折扣:%.2f%n", this.getClass().getSimpleName(), discount);
		} else {
			System.out.format("%s拒绝了折扣:%.2f%n", this.getClass().getSimpleName(), discount);
		}
	}

}
测试
public class Chain {
	private PriceHandler priceHandler;
	public void setPriceHandler(PriceHandler priceHandler) {
		this.priceHandler = priceHandler;
	}
	
	public void discount(float discount) {
		priceHandler.processDiscount(discount);
	}
	
	public static void main(String[] args) {
		Chain chain = new Chain();
		Sale sale = new Sale();
		Leader leader = new Leader();
		chain.setPriceHandler(sale);
		sale.setNext(leader);
		
		Random rand = new Random();
		for(int i = 1; i <= 10; i++) {
			System.out.print(i + ":");
			chain.discount(rand.nextFloat());
		}
		
	}

}
执行结果

在这里插入图片描述

适用场景
  1. 多个对象可以处理同一个请求,运行时自动确定具体处理的对象;
  2. 不明确具体哪个对象处理请求,此时向其中一个对象提交请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值