定义及使用场景
职责链模式避免请求发送者和接收者耦合在一起,让多个对象都有可能接受请求。并将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止,有时也称为责任链。
职责链上的每一个对象都是请求处理者。
职责链将请求的发送者和接收者解耦。
实例:
以下是用职责链模拟水果加工工厂分拣处理水果实例:
package com.chain;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractFruitSort {
private int weight;
protected List<String>fruitBox;
private AbstractFruitSort nextFruitSort;
public void getFruitBox() {
System.out.println("weight:"+weight);
System.out.println("个数:"+fruitBox.size());
for(String t:fruitBox) {
System.out.println(t+",");
}
System.out.println(" ");
}
public AbstractFruitSort(int weight) {
this.weight=weight;
fruitBox=new ArrayList<String>();
}
public void setNextSort(AbstractFruitSort nextFruitSort ) {
this.nextFruitSort=nextFruitSort;
}
public void sendFruit(int weight,String fruit) {//有水果加入时
if(this.weight<=weight)
pushBox(fruit);
else
if(nextFruitSort!=null)
nextFruitSort.sendFruit(weight,fruit);
}
abstract protected void pushBox(String fruit);
}
package com.chain;
public class BigFruitSorting extends AbstractFruitSort {
public BigFruitSorting(int weight) {
super(weight);
// TODO Auto-generated constructor stub
}
@Override
protected void pushBox(String fruit) {
// TODO Auto-generated method stub
fruitBox.add("超市:"+fruit);
}
}
package com.chain;
public class MidFruitSorting extends AbstractFruitSort {
public MidFruitSorting(int weight) {
super(weight);
// TODO Auto-generated constructor stub
}
@Override
protected void pushBox(String fruit) {
// TODO Auto-generated method stub
fruitBox.add("水果罐头:"+fruit);
}
}
package com.chain;
public class SmallFruitSorting extends AbstractFruitSort{
public SmallFruitSorting(int weight) {
super(weight);
// TODO Auto-generated constructor stub
}
@Override
protected void pushBox(String fruit) {
// TODO Auto-generated method stub
fruitBox.add("果汁:"+fruit);
}
}
package com.chain;
import java.util.Random;
public class ClientClass {
public static void main(String args[]) {
AbstractFruitSort Bfs,Mfs,Sfs;
Bfs=new BigFruitSorting(9);
Mfs=new MidFruitSorting(5);
Sfs=new SmallFruitSorting(2);
//关键代码
Bfs.setNextSort(Mfs);
Mfs.setNextSort(Sfs);
Random r=new Random();
for(int i=0;i<1000;i++) {
int weight=r.nextInt(10);
Bfs.sendFruit(weight, "橙子");
}
Bfs.getFruitBox();
Mfs.getFruitBox();
Sfs.getFruitBox();
}
}
运行结果:
学习视频指路:黑手书生
https://search.bilibili.com/all?keyword=%E9%BB%91%E6%89%8B%E4%B9%A6%E7%94%9F&from_source=nav_search_new