责任链

设计模式 / 行为型模式
image

//Handler
@interface Rescuer : NSObject
@property (nonatomic, strong) Rescuer *next;
@property (nonatomic) NSInteger code;

//HandleRequest()
- (void)help:(NSInteger)code;
- (void)toHelp;
@end

@implementation Rescuer

- (instancetype)init {
    self = [super init];
    if (self) {
        _code = -1;
    }
    return self;
}

- (void)help:(NSInteger)code {
    if (self.code == code) {
        [self toHelp];
    } else if (self.next != nil) {
        [self.next help:code];
    }
}

- (void)toHelp {
}
@end

//ConcreteHandler
@interface Firefighter : Rescuer
- (instancetype)initWithNext:(Rescuer *)next;
@end

@implementation Firefighter

- (instancetype)initWithNext:(Rescuer *)next {
    self = [super init];
    if (self) {
        self.next = next;
        self.code = 1;
    }
    return self;
}

- (void)toHelp {
    NSLog(@"call firefighters");
}
@end

//ConcreteHandler
@interface Police : Rescuer
- (instancetype)initWithNext:(Rescuer *)next;
@end

@implementation Police

- (instancetype)initWithNext:(Rescuer *)next {
    self = [super init];
    if (self) {
        self.next = next;
        self.code = 2;
    }
    return self;
}

- (void)toHelp {
    NSLog(@"call the police");
}
@end

//ConcreteHandler
@interface Ambulance : Rescuer
- (instancetype)initWithNext:(Rescuer *)next;
@end

@implementation Ambulance

- (instancetype)initWithNext:(Rescuer *)next {
    self = [super init];
    if (self) {
        self.next = next;
        self.code = 3;
    }
    return self;
}

- (void)toHelp {
    NSLog(@"call an ambulance");
}
@end

//Client
Ambulance *ambulance = [[Ambulance alloc] initWithNext:nil];
Police *police = [[Police alloc] initWithNext:ambulance];
Firefighter *firefighter = [[Firefighter alloc] initWithNext:police];
[firefighter help:1];
//printed: call firefighters
[firefighter help:2];
//printed: call the police
[firefighter help:3];
//printed: call an ambulance


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.
Read more

问题。客服部门收到大小不一的请求:小请求交给助理,较大的交给经理,很大的交给总监。如果发送请求的代码必须自己选择接收者,它就得了解每一个接收者和每一条规则。每增加一个接收者,都要修改发送者。

思路。这些接收者称为处理者,它们按固定顺序排列,这就是链。发送者只把请求交给第一个处理者。每个处理者检查请求是否归自己处理。如果是,处理者完成工作,请求不再往下传。如果不是,处理者把请求传给下一个。发送者不知道哪个处理者会作答,也不知道是否会有处理者作答。

如何阅读示例。几个处理者连成一条链。每个处理者按自己的规则判断请求是否归自己处理。客户端代码发送几个请求,每次都发往链的起点。每个请求沿着链传递,直到某个处理者接受它。在大多数语言中,每个处理者都持有下一个处理者的引用;在某些语言中,链只是一个按顺序检查的普通列表。有些示例还会发送一个没有任何处理者接受的请求,输出会报告这一点。

何时使用。当多个对象都可能处理某个请求,而这些对象的集合或顺序可能变化时,使用责任链模式。接收者始终不变时不要使用它:直接调用更简单,也更容易理解。

常见错误。忘记链的末端。这样,没有任何处理者接受的请求就会悄无声息地丢失。应事先决定末端如何处理:报错、交给默认处理者,或者给出明确的报告。