介绍
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());
}
}
}
执行结果
适用场景
- 多个对象可以处理同一个请求,运行时自动确定具体处理的对象;
- 不明确具体哪个对象处理请求,此时向其中一个对象提交请求。