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. 执行效果
相关文章推荐
- 清除IOS下input及textarea的阴影
- Ios 给imageview 添加手势没有反应
- iOS 设备信息
- 《Motion Design for iOS》(三十二)
- [iOS]毛玻璃在iOS8以上和iOS7以上的实现
- ios 数据存储方式
- iOS开发怎么判断当前页面是push方式进入还是present方式进入
- iOS Framework 制作 加载注意事项
- iOS开源代码 贝塞尔曲线与弹簧动效结合
- iOS-多线程之NSThread
- 再谈iOS 7的手势滑动返回功能
- xcode中leaks使用
- [iOS] iOS开发的22个奇葩技巧
- iOS 播放音频的几种方法
- 邓白氏编码申请最后提交资料格式
- IOS:main.m启动流程
- iOS 动画的实现
- iOS中保证线程安全的几种方式与性能对比
- iOS中日期和字符串的相互转化
- 完美解决 iOS 中只旋转自己想要旋转的屏幕