责任链模式
设计原则:遵循迪米特
常用场景:一个请求的处理需要多个对象当中的一个或几个协作处理
使用概率:15%
复杂度:中
变化点:处理链的长度与次序
选择关键点:对于每一次请求是否每个处理的对象都需要一次处理机会
逆鳞:无
主要思想:
有点类似黑盒测试,只知道现在有一个方法需要调用,但是调用到哪,谁最终完成了这个方法以及怎么完成的不知道
所谓责任链指这里的拥有这个处理方法的类有很多,但是处理需要一定的条件,比如最简单的订单买5个面包,但现在卖面包的店很多,我们需要一个一个的去买,
责任链模式,往往也会有一个调度者,这里比如是订单平台,平台负责看第一个家有5个没,没有下一家,再下一家,直到买到,但是平台的询问是有一定的顺序的,比如店1问完、店2、店3.....
这就一条链式的调用
public interface BreadStore {
public boolean sell(int sellCount);
public void setNextStore(BreadStore store);
}
public class BreadStoreImpement1 implements BreadStore {
private int breadCount;
private BreadStore nextStore;
public BreadStoreImpement1(int breadCount) {
this.breadCount = breadCount;
}
@Override
public boolean sell(int sellCount) {
if (sellCount<=breadCount) {
System.out.println("1店面包足够,售出:"+sellCount);
return true;
} else {
System.out.println("1店面包不够");
if (this.nextStore!=null) {
return this.nextStore.sell(sellCount);
}
}
return false;
}
@Override
public void setNextStore(BreadStore store) {
this.nextStore = store;
}
}
public class BreadStoreImpement2 implements BreadStore {
private int breadCount;
private BreadStore nextStore;
public BreadStoreImpement2(int breadCount) {
this.breadCount = breadCount;
}
@Override
public boolean sell(int sellCount) {
if (sellCount<=breadCount) {
System.out.println("2店面包足够,售出:"+sellCount);
return true;
}else {
System.out.println("2店面包不够");
if (this.nextStore!=null) {
return this.nextStore.sell(sellCount);
}
}
return false;
}
@Override
public void setNextStore(BreadStore store) {
this.nextStore = store;
}
}
public class BreadStoreImpement3 implements BreadStore {
private int breadCount;
private BreadStore nextStore;
public BreadStoreImpement3(int breadCount) {
this.breadCount = breadCount;
}
@Override
public boolean sell(int sellCount) {
if (sellCount<=breadCount) {
System.out.println("3店面包足够,售出:"+sellCount);
return true;
} else {
System.out.println("3店面包不够");
if (this.nextStore!=null) {
return this.nextStore.sell(sellCount);
}
}
return false;
}
@Override
public void setNextStore(BreadStore store) {
this.nextStore = store;
}
}
public class OrderManager {
private BreadStore head;
public void registeBreadStore(BreadStore... stores) {
for (int i = 0; i<stores.length; i++) {
if (this.head==null) {
this.head = stores[i];
}
if ((i+1)<stores.length) {
stores[i].setNextStore(stores[i+1]);
}
}
}
public boolean sellBread(int sellCount) {
return head.sell(sellCount);
}
}
public class Client {
public static void main(String[] args) {
BreadStoreImpement1 store1=new BreadStoreImpement1(1);
BreadStoreImpement2 store2=new BreadStoreImpement2(2);
BreadStoreImpement3 store3=new BreadStoreImpement3(3);
OrderManager manager=new OrderManager();
manager.registeBreadStore(store1,store2,store3);
manager.sellBread(2);
manager.sellBread(4);
}
}