代理模式
確定委托方和代理者雕憔。由委托方制定協(xié)議、規(guī)范接口糖声。讓任意類型的遵守協(xié)議的代理方設(shè)置為委托方需要的代理者斤彼,代理方遵守協(xié)議、實(shí)現(xiàn)協(xié)議方法蘸泻。委托方正確地設(shè)置代理琉苇,建立委托方和代理者關(guān)聯(lián)。委托方?jīng)Q定代理調(diào)用某個(gè)方法的時(shí)機(jī)悦施。應(yīng)用并扇,適用場景
老板叫老王買木頭。
委托方(老板)
//
// 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
設(shè)置代理(老板買木頭)
//
// 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
不用關(guān)心代理者抡诞,遵守協(xié)議就與委托方建立關(guān)聯(lián)穷蛹。通過協(xié)議建立通信。