设计模式之职责链模式+实例

定义及使用场景

职责链模式避免请求发送者和接收者耦合在一起,让多个对象都有可能接受请求。并将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止,有时也称为责任链。
职责链上的每一个对象都是请求处理者。
职责链将请求的发送者和接收者解耦。

实例:

以下是用职责链模拟水果加工工厂分拣处理水果实例:

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值