代理模式
确定委托方和代理者。由委托方制定协议、规范接口。让任意类型的遵守协议的代理方设置为委托方需要的代理者,代理方遵守协议、实现协议方法。委托方正确地设置代理,建立委托方和代理者关联。委托方决定代理调用某个方法的时机。应用,适用场景
老板叫老王买木头。
委托方(老板)
//
// Boss.h
// LearnDelegate
//
// Created by 印林泉 on 2017/3/2.
// Copyright © 2017年 yiq. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol BossDelegate <NSObject>
- (void)buyWood;
@end
@interface Boss : NSObject
@property (nonatomic, strong) id<BossDelegate> delegate;
- (void)sendCommand;
@end
//
// Boss.m
// LearnDelegate
//
// Created by 印林泉 on 2017/3/2.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Boss.h"
@implementation Boss
- (void)sendCommand {
NSLog(@"send command");
[self.delegate buyWood];
}
@end
代理者(老王)
//
// Worker.h
// LearnDelegate
//
// Created by 印林泉 on 2017/3/2.
// Copyright © 2017年 yiq. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Boss.h"
@interface Worker : NSObject<BossDelegate>
@end
//
// Worker.m
// LearnDelegate
//
// Created by 印林泉 on 2017/3/2.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "Worker.h"
@implementation Worker
- (void)buyWood {
NSLog(@"buy wood");
}
@end
设置代理(老板买木头)
//
// ViewController.m
// LearnDelegate
//
// Created by 印林泉 on 2017/3/2.
// Copyright © 2017年 yiq. All rights reserved.
//
#import "ViewController.h"
#import "Boss.h"
#import "Worker.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Worker *worker = [[Worker alloc] init];
Boss *boss = [[Boss alloc] init];
[boss setDelegate:worker];
[boss sendCommand];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
不用关心代理者,遵守协议就与委托方建立关联。通过协议建立通信。