您的位置:首页 > 其它

设计模式:代理

2015-12-03 17:06 120 查看
1.通过中介公司找房子

//Person.h
#import <Foundation/Foundation.h>
@class Person;

@protocol PersonProtocol <NSObject>

-(void)personWantToFindApartment:(Person *)person;

@end

//Person要找房子
@interface Person : NSObject

@property (nonatomic, assign) NSString *name;

//找房子的代理
@property (nonatomic, strong) id<PersonProtocol>delegate;

//构造方法
-(instancetype)initWithName:(NSString *)name withDelegate:(id<PersonProtocol>)delegate;

//找房子
-(void)wantToFindApartment;

@end

//Person.m
#import "Person.h"

//定义私有方法
@interface Person()

-(void)startFindApartment:(NSTimer *)timer;

@end

//实现Person
@implementation Person

-(instancetype) initWithName:(NSString *)name withDelegate:(id<PersonProtocol>)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:@"代理找房子" repeats:YES];
}

//实现私有方法
-(void) startFindApartment:(NSTimer *)timer{
NSString *info = [timer userInfo];
NSLog(@"1");
if ([self.delegate respondsToSelector:@selector(personWantToFindApartment:)]) {
NSLog(@"%@",info);
[self.delegate personWantToFindApartment:self];
}
}

@end

//Agent.h
//代理
#import <Foundation/Foundation.h>
@protocol PersonProtocol;

@interface Agent : NSObject<PersonProtocol>

@end

//Agent.m
#import "Agent.h"
#import "Person.h"

@implementation Agent

-(void)personWantToFindApartment:(Person *)person{
NSLog(@"%s 代理帮忙找房子",__func__);
}

@end

//main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Agent.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
Agent *a = [[Agent alloc] init];
Person *p = [[Person alloc] initWithName:@"keen" withDelegate:a];

[p wantToFindApartment];

[[NSRunLoop currentRunLoop] run];
}

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: