设计模式学习笔记——10 责任链模式

责任链模式

定义

责任链模式使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象连城一条链,并沿着这条链传递该请求,直到有对象处理它为止。

优点

降低耦合度。它将请求的发送者和接收者解耦
简化了对象,使得对象不需要知道链的结构
增强给对象指派职责的灵活性,允许动态地新增或者删除责任链
增加新的请求处理类方便

缺点

每个请求都是将责任链从头遍历到尾,如果较长,性能有影响
调试时不方便,调用逻辑复杂,可能会造成循环调用

在这里插入图片描述

public class ChainType {

	public static int type_1 = 1;
	public static int type_2 = 2;
	public static int type_3 = 3;
	
	public static int getChainType(Handler handler){
		
		if(handler instanceof Handler1){
			return type_1;
		}
		if(handler instanceof Handler2){
			return type_2;
		}
		if(handler instanceof Handler3){
			return type_3;
		}
		return -1;
	}
}

public class Response {

	private int chainType;
	
	private String status;

	public int getChainType() {
		return chainType;
	}

	public void setChainType(int chainType) {
		this.chainType = chainType;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
}

public abstract class Handler {

	private Handler nextHandler;
	private int chainType;
	
	protected void setNextHandler(Handler nextHandler) {
		this.nextHandler = nextHandler;
	}
	
	public Response handleMessage(Response response){
		if(getChainType()==response.getChainType()){
			return this.excute(response);
		}else{
			return this.nextHandler.handleMessage(response);
		}
	} 
	
	protected abstract Response excute(Response response);

	public int getChainType(){
		return ChainType.getChainType(this);
	}
}

public class Handler1 extends Handler{

	@Override
	protected Response excute(Response response) {
		response.setStatus("Handler1 excuted");
		return response;
	}

}

public class Handler2 extends Handler{

	@Override
	protected Response excute(Response response) {
		response.setStatus("Handler2 excuted");
		return response;
	}

}


public class Handler3 extends Handler{

	@Override
	protected Response excute(Response response) {
		response.setStatus("Handler1 excuted");
		return response;
	}

}

public class Client {

	public static void main(String[] args) {


		Response response = new Response();
		response.setChainType(ChainType.type_2);
		Handler handle1 = new Handler1();
		Handler handle2 = new Handler2();
		Handler handle3 = new Handler3();
		
		handle1.setNextHandler(handle2);
		handle2.setNextHandler(handle3);
		handle1.handleMessage(response);
		System.out.println(response.getStatus());
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值