iOS-delegate设计模式
在iOS代理设计模式中可以把其分解为:host delegate actions proctocol
host:该实例的角色是一个消费者,它消费的就是proctocol提供的功能
delegate:就是一个劳动者,它主要就是提供proctocol服务,就相当实现协议
action:就相当于delegate的具体服务实现
代理模式的使用流程为:
host持有delegate引用,
delegate实现协议的功能,就是action的具体实现,
action具体的服务。
你什么时候想消费了就这样:
[host.delegate action] 这个由host调用,来达到对代理的消费。
例子:
host类实现:
头文件 :
//host想要的服务协议@protocol hostDelegate <NSObject>-(void)sayHelloService;-(void)sayGoodByeService;@end@interface Host : NSObject@property (nonatomic,assign)id<hostDelegate> delegate;//消费函数-(void)customerHelloService;//消费函数-(void)customerGoodbyeService;@end实现文件:
@implementation Host-(void)customerHelloService{if ([self.delegate respondsToSelector:@selector(sayHelloService)]) {//消费代理的服务[self.delegate sayHelloService];}}-(void)customerGoodbyeService{if ([self.delegate respondsToSelector:@selector(sayGoodByeService)]) {//消费代理的服务[self.delegate sayGoodByeService];}}@end
代理文件的实现
代理头文件:
//实现协议,,相当于提供了服务@interface delegateAgent : NSObject<hostDelegate>@end代理实现文件:@implementation delegateAgent//提供的具体服务-(void)sayGoodByeService{NSLog(@"good bye host");}//提供的具体服务-(void)sayHelloService{NSLog(@"hello host");}@end
具体的代理模式的联合使用:
//创建一个代理服务实例delegateAgent *dlgte =[[delegateAgent alloc]init];//创建一个消费者Host *host = [[Host alloc]init];//消费者到这家服务点消费host.delegate = dlgte;//消费者消费了下面的服务[host customerGoodbyeService];[host customerHelloService];
代理者提供的具体服务为输出结果:
代理输出的服务:
2015-03-29 17:45:50.890 Target_action[2082:102628] good bye host
2015-03-29 17:45:50.891 Target_action[2082:102628] hello host
代理模式的运行内存状态:
如果我们想要更多的玫瑰花,就必须种植更多的玫瑰树。