OC 代理模式
2018-07-24 本文已影响16人
CaptainRoy
- 举个例子, 一个老总通过坐车去出差,但是一般自己是不开车的,因此委托司机开车送他出差
司机类
- Driver.h
#import <Foundation/Foundation.h>
@interface Driver : NSObject
-(void)sendBoss;
@end
- Driver.m
#import "Driver.h"
@implementation Driver
-(void)sendBoss
{
NSLog(@"汽车 送老板");
}
@end
老总类
- Boss.h
#import <Foundation/Foundation.h>
@class Driver;
@interface Boss : NSObject
@property(nonatomic,strong)Driver *driver;
-(void)startBuinessTrip;
@end
- Boss.m
#import "Boss.h"
#import "Driver.h"
@implementation Boss
-(void)startBuinessTrip
{
self.driver = [[Driver alloc] init];
[self.driver sendBoss];
}
@end
Boss *boss = [[Boss alloc] init];
[boss startBuinessTrip]; // 汽车 送老板
但是上面的例子必须把代理方要具体实现的方法写出来,不利于低耦合,换个角色同样也要写出具体方法来,因此可以通过一个协议来实现代理的具体内容
- 送人工具协议
#import <Foundation/Foundation.h>
@protocol DriveProtocol <NSObject>
// 不同类型的交通工具送人
-(void)sendPersonByTool:(NSString *)tool;
@end
- Driver.h
#import <Foundation/Foundation.h>
#import "DriveProtocol.h"
@interface Driver : NSObject
@property(nonatomic,weak) id<DriveProtocol> delegate;
-(void)sendBoss;
@end
- Driver.m
#import "Driver.h"
@implementation Driver
-(void)sendBoss
{
if (self.delegate && [self.delegate respondsToSelector:@selector(sendPersonByTool:)]) {
[self.delegate sendPersonByTool:@"汽车"];
}
}
@end
- Boss.h
#import <Foundation/Foundation.h>
@class Driver;
@interface Boss : NSObject
@property(nonatomic,strong)Driver *driver;
-(void)startBuinessTrip;
@end
- Boss.m
#import "Boss.h"
#import "Driver.h"
@interface Boss ()<DriveProtocol>
@end
@implementation Boss
-(void)startBuinessTrip
{
self.driver = [[Driver alloc] init];
self.driver.delegate = self;
[self.driver sendBoss];
}
-(void)sendPersonByTool:(NSString *)tool
{
NSLog(@" %@ 送老板",tool);
}
@end
Boss *boss = [[Boss alloc] init];
[boss startBuinessTrip]; // 汽车 送老板