首页 > 其他 > 详细

案例:找房子(代理设计模式)

时间:2015-12-03 18:59:24      阅读:316      评论:0      收藏:0      [点我收藏+]

 

通过中介公司找房子

//1:协议声明:
#import <Foundation/Foundation.h>  
@protocol FindApartment <NSObject> 
  -(void)findApartment; @end //2:代理角色声明(Agent.h)头文件声明 #import <Foundation/Foundation.h> #import "FindApartment.h" @interface Agent : NSObject <FindApartment> @end //3:代理角色实现(Agent.m)实现文件 #import "Agent.h" @implementation Agent -(void)findApartment{ NSLog(@"findApartment"); } @end //4:真实角色声明(Person.h)头文件声明 #import <Foundation/Foundation.h> #import "FindApartment.h" @interface Person : NSObject { @private NSString *_name; id<FindApartment> _delegate; //委托人(具备中介找房子的协议) } @property(nonatomic,copy) NSString *name; @property(nonatomic,assign)id<FindApartment> delegate; -(id)initWithName:(NSString *)name withDelegate:(id<FindApartment>) delegate; -(void)wantToFindApartment; @end //5:真实角色实现(Person.m)实现 #import "Person.h" //定义私有方法 @interface Person() -(void)startFindApartment:(NSTimer *)timer; @end @implementation Person @synthesize name=_name; @synthesize delegate=_delegate; -(id)initWithName:(NSString *)name withDelegate:(id<FindApartment>) delegate{ self=[super init]; if(self){ self.name=name; self.delegate=delegate; } return self; } -(void)wantToFindApartment{ [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:@"Hello" repeats:YES]; } -(void)startFindApartment:(NSTimer *)timer{ //NSString *userInfo=[timer userInfo]; [self.delegate findApartment]; } @end //6:测试代理main.m方法 #import <Foundation/Foundation.h> #import "Person.h" #import "Agent.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); Agent *agent=[[Agent alloc]init]; Person *jack=[[Person alloc]initWithName:@"jack" withDelegate:agent]; [jack wantToFindApartment]; [[NSRunLoop currentRunLoop]run]; [jack autorelease]; }
return 0; }

 

案例:找房子(代理设计模式)

原文:http://www.cnblogs.com/KeenLeung/p/5016895.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!