Chain of Responsibility(职责链模式)
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
iOS事件的传递和响应就是职责链模式的实现。
VC.m
HCDCommonManager *common = [[HCDCommonManager alloc]initWithName:@"经理"];
HCDMajorManager *majon = [[HCDMajorManager alloc]initWithName:@"总监"];
HCDGenaralManager *genaral = [[HCDGenaralManager alloc]initWithName:@"总经理"];
common.superior = majon;
majon.superior = genaral;
HCDReuquest *request = [[HCDReuquest alloc]init];
request.requestType = @"请假";
request.number = 5;
[common dealRequest:request];
request.number = 20;
[common dealRequest:request];
request.number = 220;
[common dealRequest:request];
request.number = 1200;
[common dealRequest:request];
HCDMnager.h
@interface HCDMnager : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,strong)HCDMnager *superior;
-(instancetype)initWithName:(NSString *)name;
-(void)dealRequest:(HCDReuquest *)request;
@end
HCDMnager.m
@implementation HCDMnager
-(instancetype)initWithName:(NSString *)name{
self = [super init];
if (self) {
_name = name;
}
return self;
}
-(void)dealRequest:(HCDReuquest *)request{
}
@end
HCDCommonManager.m
@implementation HCDCommonManager
-(void)dealRequest:(HCDReuquest *)request{
if ([request.requestType isEqualToString:@"请假"] && request.number < 10) {
NSLog(@"%@处理了%@,时间是%ld",self.name,request.requestType,request.number);
}else{
[self.superior dealRequest:request];
}
}
@end
网友评论