Patterns / Behavioral patterns
image

//Handler
@interface Rescuer : NSObject
@property (nonatomic, strongRescuer *next;
@property (nonatomicNSInteger 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.