OC组件化04:面向协议Protocol Class的使用
面向协议 Protocol Class
实现方式
优点
缺点
示例
1 2 3 4 5 6 7 8 9 10
| // 将各个模块的协议统一放在一个文件中 ,在各个模块中依赖这个文件,实现其协议 @protocol OneMoudleProtocol <NSObject> @required // 返回模块one + (UIViewController *)oneMoudleVC; @end
@protocol OneDetailMoudleProtocol <NSObject> @required + (UIViewController *)oneDetailMoudleVCWithParas:(NSDictionary *)paras; @end
|
ZJMediator.h 文件下:
1 2 3 4 5 6 7 8
| @interface ZJMediator : NSObject // 单例 + (instancetype)shareManager; // 注册绑定 - (void)registerProtocol:(Protocol *)protocol class:(Class)cls; // 获取类 - (Class)classFromProtocol:(Protocol *)protocol; @end
|
ZJMediator.m 文件下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #import "ZJMediator.h" @interface ZJMediator () @property (nonatomic,strong)NSMutableDictionary * protocolCache; @end @implementation ZJMediator + (instancetype)shareManager{ static ZJMediator * mediator; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ mediator = [[ZJMediator alloc] init]; }); return mediator; } // 注册绑定 - (void)registerProtocol:(Protocol *)protocol class:(Class)cls{ if (protocol && cls) { [self.protocolCache setObject:cls forKey:NSStringFromProtocol(protocol)]; } } // 获取类 - (Class)classFromProtocol:(Protocol *)protocol{ return [self.protocolCache objectForKey:NSStringFromProtocol(protocol)]; } // 懒加载 - (NSMutableDictionary *)protocolCache{ if (!_protocolCache) { _protocolCache = @{}.mutableCopy; } return _protocolCache; } @end
|
- 创建
OneDetailMoudleEntry
模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #import "OneDetailMoudleEntry.h" #import "ZJOneDetailViewController.h"
@interface OneDetailMoudleEntry ()<OneDetailMoudleProtocol>
@end @implementation OneDetailMoudleEntry + (void)load{ [[ZJMediator shareManager] registerProtocol:@protocol(OneDetailMoudleProtocol) class:[self class]]; } // 继承 + (UIViewController *)WithParas:(NSDictionary *)paras{ ZJOneDetailViewController * detailVC = [[ZJOneDetailViewController alloc] init]; detailVC.name = paras[@"name"]; detailVC.age = params[@"age"]; return detailVC; } @end
|
1 2 3 4 5 6 7
| //下一页的点击事件 - (void)next:(UIButton *)sender{ Class cls = [[ZJMediator shareManager] classFromProtocol:@protocol(OneDetailMoudleProtocol)]; UIViewController * detailVC = [cls oneDetailMoudleVCWithParas:@{@"name":@"ZJ",@"age":30}]; [self.navigationController pushViewController:detailVC animated:YES]; }
|
- Post title:OC组件化04:面向协议Protocol Class的使用
- Post author:张建
- Create time:2023-03-04 16:16:42
-
Post link:https://redefine.ohevan.com/2023/03/04/OC组件化/OC组件化04:面向协议Protocol-Class的使用/
-
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.