前言
之前很火的组件化的思想,导致出来很多解决方案。
有模仿web的思想的urlRouter,还有类似设计模式中的中介者模式。
个人感觉这个中介者方法论很适合解决这个场景,多个模块之前的依赖造成的混乱。
类似思路
- 比如A模块需要跳转B模块,则告诉中介者我要调用B模块
UIViewController *viewController = [WCSServiceMediator durableGoodsRecipients_viewControllerWithTitle:@"耐耗品领用Test" extraA:@""];
[self.navigationController pushViewController:viewController animated:YES];
注意:这些通信的方法是在中介者里的本质上
- 中介者中的初始化各个模块的方法本质上是这个,但是这样会依赖很多模块。
+ (UIViewController *)moduleControllerWithParams:(NSDictionary *)params {
WCSDurableGoodsRecipientsListController *durableGoodsRecipientsListController = [[UIStoryboard storyboardWithName:@"WCSDurableGoodsRecipients" bundle:nil] instantiateViewControllerWithIdentifier:@"WCSDurableGoodsRecipientsListControllerID"];
durableGoodsRecipientsListController.paramsDic = params;
return durableGoodsRecipientsListController;
}
- 为了感官上解除中介者对各模块的依赖,通过runtime + target-action解除
+ (UIViewController *)viewControllerWithModuleClass:(NSString *)moduleClass selector:(NSString *)selector params:(NSDictionary *)params {
if (moduleClass.length == 0 || selector.length == 0 || !params) {
return nil;
}
//target-action解除Mediator对ModuleX的感官依赖,运行时仍存在依赖
Class cls = NSClassFromString(moduleClass);
SEL sel = NSSelectorFromString(selector);
if (!cls || !sel) {
return nil;
}
if ([cls respondsToSelector:sel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
return [cls performSelector:sel withObject:params];
#pragma clang diagnostic pop
}
return nil;
}
- 但是如果模块太多中介者太臃肿,所以针对每个组件模块写一个类别。
#import "WCSServiceMediator+WCSDurableGoodsRecipients.h"
@implementation WCSServiceMediator (WCSDurableGoodsRecipients)
+ (UIViewController *)durableGoodsRecipients_viewControllerWithTitle:(NSString *)title extraA:(NSString *)extraA
{
return [[self class] viewControllerWithModuleClass:@"WCSDurableGoodsRecipients" selector:@"moduleControllerWithParams:" params:@{@"title": title, @"extraA": extraA}];
}
@end
总结:
模块通过中介者通信,中介者通过 runtime 接口解耦,通过 target-action 简化写法,通过 category 感官上分离组件接口代码。
前后对比:
参考链接:
https://github.com/casatwy/CTMediator/tree/master/CTMediator
网友评论