Proxy(代理模式)
为其他对象提供一种代理以控制对这个对象的访问。
UITableView的delegate和dataSource,都是通过代理对象来控制对UITableView的访问。
VC.m
HCDschoolGirl *girl = [[HCDschoolGirl alloc]init];
girl.name = @"哈哈哈哈哈";
HCDproxy *proxy = [[HCDproxy alloc]initWithSchoolGirl:girl];
[proxy giveFlowers];
[proxy giveDolls];
[proxy giveChocolate];
HCDgiveGift.h // 方法列表
@protocol HCDgiveGift <NSObject>
/// 送洋娃娃
- (void)giveDolls;
/// 送鲜花
- (void)giveFlowers;
/// 送巧克力
- (void)giveChocolate;
@end
HCDproxy.h // 代理类
@interface HCDproxy : NSObject<HCDgiveGift>
-(instancetype)initWithSchoolGirl:(HCDschoolGirl *)schoolGirl;
@end
HCDproxy.m
@interface HCDproxy ()
@property (strong, nonatomic) HCDpursuit *pursuit;
@end
@implementation HCDproxy
- (instancetype)initWithSchoolGirl:(HCDschoolGirl *)schoolGirl {
self = [super init];
if (self) {
self.pursuit = [[HCDpursuit alloc] initWithSchoolGirl:schoolGirl];
}
return self;
}
- (void)giveDolls {
[self.pursuit giveDolls];
}
- (void)giveFlowers {
[self.pursuit giveFlowers];
}
- (void)giveChocolate {
[self.pursuit giveChocolate];
}
@end
HCDpursuit.h // 实现类
@interface HCDpursuit : NSObject<HCDgiveGift>
-(instancetype)initWithSchoolGirl:(HCDschoolGirl *)schoolGirl;
@end
HCDpursuit.m
@interface HCDpursuit ()
@property(nonatomic,strong)HCDschoolGirl *schoolGirl;
@end
@implementation HCDpursuit
-(instancetype)initWithSchoolGirl:(HCDschoolGirl *)schoolGirl{
self = [super init];
if (self) {
_schoolGirl = schoolGirl;
}
return self;
}
-(void)giveChocolate{
NSLog(@"送你巧克力%@",self.schoolGirl.name);
}
-(void)giveDolls{
NSLog(@"送你洋娃娃%@",self.schoolGirl.name);
}
-(void)giveFlowers{
NSLog(@"送你玫瑰花%@",self.schoolGirl.name);
}
@end