码迷,mamicode.com
首页 > 其他好文 > 详细

代理模式

时间:2015-12-25 19:11:06      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

1.一般把协议放在代理中(见Person.h)

2.接收的类型用id 并且服从协议(@property(nonatomic,assign)id <agentDelegate> delegate)

3.一定要确保对象实现了方法([self.delegate respondsToSelector:@selector(call:)])

Person.h

#import <Foundation/Foundation.h>

#import "Agent.h"

@interface Person : NSObject <agentDelegate> 

-(void)needHouse;

-(void)call:(NSString *)message;

@end

Person.m 

#import "Person.h"

#import "Agent.h" 

@implementation Person

-(void)needHouse{

    Agent * ag = [[Agent alloc]init];

    ag.delegate = self;

    [ag rentHouse];   

}

-(void)call:(NSString *)message{

    NSLog(@"%@",message);

} 

@end

Agent.h

@protocol agentDelegate <NSObject>

@optional

-(void)call:(NSString*)message;

@end

 

@interface Agent : NSObject

@property(nonatomic,assign)id <agentDelegate> delegate;

-(void)rentHouse;

@end

Agent.m 

@implementation Agent

-(void)rentHouse{

    NSLog(@"正在租房子");

    if ([self.delegate respondsToSelector:@selector(call:)]){

        [self.delegate call:@"租到房子了"];

    } 

}

@end

代理模式

标签:

原文地址:http://www.cnblogs.com/huoran1120/p/5076312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!