不务正业之OC(十五)–代理设计模式

什么是代理设计模式:两个对象相互协作,完成共同的目标。
比如:A需要开发一个app,但又不会,把这个需求发到网上去,这时B看到A的需求,B说我能完成这个任务,B接到这个任务并完成后,通知A。

特点:
1、减小对象之间的耦合度
2、无需子类化

代理设计模式按书上例子写一下:Person实例要找房子,但Person实例没有这个能力,那就委托给Agent类去找房子,找到房子后,和Person实例说,我找到房子
Person类、Agent类、FindApartment协议

 
//  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;
//初始化Person对象name及委托人(找谁来找房子)
- (id) initWithName:(NSString *)name withDelegate:(id <FindApartment>) delegate;
//Person对象需求
- (void) wantToFindApartment;
 
@end
 
//  Person.m
 
#import "Person.h"
 
@implementation Person
 
@synthesize name = _name;
@synthesize delegate = _delegate;
 
- (id) initWithName:(NSString *)name withDelegate:(id <FindApartment>) delegate{
 
    if (self = [super init]) {
        self.name = name;
        self.delegate = delegate;
    }
    return self;
}
 
- (void) wantToFindApartment{
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:nil repeats:YES];
}
 
- (void)startFindApartment:(NSTimer *) timer{
    [self.delegate findApartment];
 
}
 
@end
 
//  Agent.h
 
#import <Foundation/Foundation.h>
#import "FindApartment.h"
 
@interface Agent : NSObject<FindApartment>
 
@end
 
//  Agent.m
 
#import "Agent.h"
//委托人需要实现<FindApartment>中定义方法,Agent有这个能力来找房子
@implementation Agent
- (void)findApartment{
    NSLog(@"find");
}
 
@end
 
//  FindApartment.h
 
#import <Foundation/Foundation.h>
//协议定义
@protocol FindApartment <NSObject>
 
- (void)findApartment;
 
@end
 
 
//  main.m
//  Delegate
 
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Agent.h"
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        Agent *agent = [[Agent alloc] init];
        //委托给agent来找房子
        Person *jack = [[Person alloc] initWithName:@"jack" withDelegate:agent];
        //调用wantToFindApartment会触发定时器,每隔2s钟调用delegate(这个delegate就是agent)会调用findApartment方法
        [jack wantToFindApartment];
 
        [[NSRunLoop currentRunLoop] run];
 
    }
    return 0;
}

Post a Comment