1700464397
设计模式之禅 16.2 责任链模式的定义
1700464398
1700464399
责任链模式定义如下:
1700464400
1700464401
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.Chain the receiving objects and pass the request along the chain until an object handles it.(使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。)
1700464402
1700464403
责任链模式的重点是在“链”上,由一条链去处理相似的请求在链中决定谁来处理这个请求,并返回相应的结果,其通用类图如图16-4所示。
1700464404
1700464405
1700464406
1700464407
1700464408
图16-4 责任链模式通用类图
1700464409
1700464410
责任链模式的核心在“链”上,“链”是由多个处理者ConcreteHandler组成的,我们先来看抽象Handler类,如代码清单16-14所示。
1700464411
1700464412
代码清单16-14 抽象处理者
1700464413
1700464414
public abstract class Handler{
1700464415
1700464416
private Handler nextHandler;
1700464417
1700464418
//每个处理者都必须对请求做出处理
1700464419
1700464420
public final Response handleMessage(Request request){
1700464421
1700464422
Response response=null;
1700464423
1700464424
//判断是否是自己的处理级别
1700464425
1700464426
if(this.getHandlerLevel().equals(request.getRequestLevel())){
1700464427
1700464428
response=this.echo(request);
1700464429
1700464430
}else{//不属于自己的处理级别
1700464431
1700464432
//判断是否有下一个处理者
1700464433
1700464434
if(this.nextHandler!=null){
1700464435
1700464436
response=this.nextHandler.handleMessage(request);
1700464437
1700464438
}else{
1700464439
1700464440
//没有适当的处理者,业务自行处理
1700464441
1700464442
}
1700464443
1700464444
}
1700464445
[
上一页 ]
[ :1.700464396e+09 ]
[
下一页 ]