iOS-delegate设计模式


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


代理模式的运行内存状态:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值