您的位置:首页 > 移动开发 > IOS开发

iOS 代理委托设计模式

2016-07-07 11:02 477 查看

1.概念

A类想做某事,但是A类不具备做某事的能力(方法);

B类能做某事,但是B类没有做某事的意愿;

故,A类就拜托B类帮助自己做某事的过程叫 【代理委托模式】

2.术语

1. 委托人:

1. 委托人需要说明想要别人(即执行人)帮助自己做什么事情:即: 委托人需要定义协议

2. 委托人需要指定是谁帮我做事情:即: 委托人要持有执行人的引用

3. 委托人需要摆脱执行人做某事: 即:委托人需要提供委托的具体过程

// 1. 委托人想要拜托执行人想要做的事
@protocol EntrusterDelegate <NSObject>

- (void)showMsg;

@end
// 2. 设置执行人是谁,设置想要委托的执行人是谁,这里不知道执行人是谁,所以使用id类型,并且要求执行人要实现这个协议
@property (weak, nonatomic) id<EntrusterDelegate> delegate;
// 3. 拜托执行人做某事:提供委托的具体过程
- (void)entrustImplementerDoSomething;


2. 执行人:

1. 执行人要知道都需要做什么事情; 即:执行人要遵守协议

2. 执行人要具体做这些事情;即:执行人要实现协议

// 1. 遵守协议
@interface ImplementerViewController : UIViewController <EntrusterDelegate>

@end
// 2. 实现协议
- (void)showMsg {
NSLog(@"我是执行人,您委托我的事情已经帮你做了...");
}


示例代码

1. 委托人代码

#import <UIKit/UIKit.h>

// 1.委托人想要拜托执行人想要做的事
@protocol EntrusterDelegate <NSObject>

- (void)showMsg;

@end

// 委托人:想要做某事,但是并没有这个方法的实现,于是就委托别人来代替他来实现
@interface EntrusterViewController : UIViewController

// 2. 设置执行人是谁,设置想要委托的执行人是谁,这里不知道执行人是谁,所以使用id类型,并且要求执行人要实现这个协议 @property (weak, nonatomic) id<EntrusterDelegate> delegate;

// 3. 拜托执行人做某事:提供委托的具体过程 - (void)entrustImplementerDoSomething;

@end
#import "EntrusterViewController.h"
@implementation EntrusterViewController

- (void)entrustImplementerDoSomething {
// 判断执行人能否做某事
if ([self.delegate respondsToSelector:@selector(showMsg)]) {
[self.delegate showMsg];
}
}
@end


2. 执行人代码

#import <UIKit/UIKit.h>
#import "EntrusterViewController.h"

// 执行人:遵守协议,并实现协议
@interface ImplementerViewController : UIViewController <EntrusterDelegate>

@end
#import "ImplementerViewController.h"

@implementation ImplementerViewController

- (void)showMsg {
NSLog(@"我是执行人,您委托我的事情已经帮你做了...");
}

@end


3. 具体使用代码

#import "ViewController.h"
#import "EntrusterViewController.h"
#import "ImplementerViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// 模拟整个委托过程

// 1.设置委托人的执行人是谁
ImplementerViewController *implementer = [[ImplementerViewController alloc] init];
EntrusterViewController *entrustr = [[EntrusterViewController alloc] init];
entrustr.delegate = implementer;

// 2.委托人执行 执行人的方法
[entrustr entrustImplementerDoSomething];
}

@end


4. 执行效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: