OC 代理模式

2018-07-24  本文已影响16人  CaptainRoy
司机类
#import <Foundation/Foundation.h>

@interface Driver : NSObject

-(void)sendBoss;

@end
#import "Driver.h"

@implementation Driver

-(void)sendBoss
{
    NSLog(@"汽车 送老板");
}

@end
老总类
#import <Foundation/Foundation.h>

@class Driver;

@interface Boss : NSObject

@property(nonatomic,strong)Driver *driver;

-(void)startBuinessTrip;

@end
#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
#import <Foundation/Foundation.h>

#import "DriveProtocol.h"

@interface Driver : NSObject

@property(nonatomic,weak) id<DriveProtocol> delegate;

-(void)sendBoss;

@end
#import "Driver.h"

@implementation Driver

-(void)sendBoss
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendPersonByTool:)]) {
        [self.delegate sendPersonByTool:@"汽车"];
    }
}

@end
#import <Foundation/Foundation.h>

@class Driver;

@interface Boss : NSObject

@property(nonatomic,strong)Driver *driver;

-(void)startBuinessTrip;

@end
#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]; // 汽车 送老板
上一篇下一篇

猜你喜欢

热点阅读