一个 APP 有多个模块,模块之间会通信,互相调用. 一个功能复杂的界面难免会在里边引入很多其他类的头文件, 使得代码耦合度很高, 为了解决这个问题需要引入组件化方案
首先需要一个Mediator类
//Mediator.h 类
@interfaceMediator :NSObject
+ (Mediator*)shareInstance;
- (id)performTarget:(NSString*)target action:(NSString*)action param:(NSDictionary*)parame;
@end
#import "Mediator.h"
@implementation Mediator
+ (Mediator*)shareInstance {
staticMediator*s =nil;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
s = [[Mediatoralloc]init];
});
returns;
}
//抽离出来所有的target以及action
- (id)performTarget:(NSString*)target action:(NSString*)action param:(NSDictionary*)parame {
Class cls =NSClassFromString(target);
idtarget Obj = [[cls alloc]init];
SEL actionSEL = NSSelectorFromString([NSString stringWithFormat:@"action_%@", action]);
if([targetObj respondsToSelector: actionSEL]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
return [targetObj performSelector:actionSEL withObject:parame];
#pragma clang diagnostic pop
}
return nil;
}
对于每个模块都需要有自己的mediator, 所以对于每个模块都写一个分类
#import "Mediator.h"
@interfaceMediator (ViewControllerAction)
- (UIViewController*)Mediator_viewController1With:(NSDictionary*)parame;
- (UIViewController*)Mediator_viewController2With:(NSDictionary*)parame;
@end
#import "Mediator+ViewControllerAction.h"
@implementationMediator (ViewControllerAction)
- (UIViewController*)Mediator_viewController1With:(NSDictionary*)parame {
UIViewController *VC = [self performTarget:@"ViewController1" action:@"viewcontroller1WithId:" param:parame];
returnVC;
}
- (UIViewController*)Mediator_viewController2With:(NSDictionary*)parame {
UIViewController *VC = [self performTarget:@"ViewController2" action:@"viewcontroller2WithId:" param:parame];
returnVC;
}
@end
在需要被创建的类里边写各自需要的代码逻辑 如下
@implementationViewController1
- (UIViewController*)action_viewcontroller1WithId:(NSMutableDictionary*)param {
ViewController1 *VC = [[ViewController1 alloc] init];
VC.ID= param[@"id"];
returnVC;
}
在需要被创建的类里边写各自需要的代码逻辑 如下
@implementationViewController2
- (UIViewController*)action_viewcontroller2WithId:(NSMutableDictionary*)param {
ViewController2 *VC = [[ViewController2 alloc] init];
VC.ID= param[@"id"];
returnVC;
}
最后在需要创建的地方调用就可以了 如:
UIViewCOntroller *VC = [[Mediator shareInstance] Mediator_viewController1With:{@"id":@"1"}];
这样就拿到了需要创建的对象
网友评论