职责链模式(Chain of Responsibility)

职责链模式的意图:使多个对象都有机会处理请求,避免请求发送者和接受者之间的高耦合关系;将这些接受者连成一条链,将请求沿着这条链传递下去,直到有一个对象处理它为止

该模式的UML图如下:

Handler:包含接受者的统一处理方法声明handlerequest(),其中也可以添加sucessor字段,用于指定其后继者(在Java中,此时Handler为抽象类;当它为接口时,由于接口中不能包含字段,所以不能指定后继者)

ConcreteHandler:具体的请求处理者(接受者),实现Handler中声明的handlerrequest方法,当它不能处理当前请求时,发送给他的后继者处理

下面看一个示例代码:

abstract class Doctor{
	protected Doctor nextDoctor;
	
	public void setNextDoctor(Doctor next){
		nextDoctor = next;
	}
	
	public abstract void handlePatient(String patient);
}

class SurfaceDoctor extends Doctor {

	@Override
	public void handlePatient(String patient) {
		if(patient == null){
			System.out.println("Patient is null");
		}
		if(patient != null && patient.equals("Surface")){
			System.out.println("Patient is handled by SurfaceDoctor");
		}
		else{
			nextDoctor.handlePatient(patient);
		}
	}
	
}

class HeartDoctor extends Doctor {

	@Override
	public void handlePatient(String patient) {
		if(patient == null){
			System.out.println("Patient is null");
		}
		if(patient != null && patient.equals("Heart")){
			System.out.println("Patient is handled by HeartDoctor");
		}
		else{
			nextDoctor.handlePatient(patient);
		}
	}
	
}

public class ChainOfResponsibility {
	public static void main(String[] args){
		Doctor d1 = new SurfaceDoctor();
		Doctor d2 = new HeartDoctor();
		d1.setNextDoctor(d2);
		d1.handlePatient("Heart");
	}
}
职责链模式的好处是:

1. 各个接受者的职责明确,不会造成把所有逻辑堆在一个类中导致维护困难;在职责链模式中,需要增加逻辑只需要在链表中加一个节点即可

2. 客户端和接受者代码的松耦合,因为对于客户端来说,该职责链中只需要有一个节点能够处理其请求即可,不要求客户端显式指定接受者

注意:对于职责链模式需要注意的一点是确保客户端的请求能够被其中某个节点处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值