组件化开发实践

组件化思路很多,文章也很多,参考之后选择 casatwy / CTMediator 作为最佳实践
https://github.com/casatwy/CTMediator

一、基础

组件化主要为了解决项目变大,模块变多,相互依赖,工程恶化的问题;

核心思想:
1、模块独立,仅开放部分入口供外部调用
2、使用中间者模式,统一管理模块开放入口
3、中间者运用 runtime 动态创建,切断相互关联,彻底独立模块
4、使用 pod 管理模块库,便捷高效

二、CTMediator

2.1 核心部分

使用 target-action 方式实现对象方法调用
结合 NSClassFromString、NSSelectorFromString 反向实现 Class 和 SEL 的获取
完全切断了中间者对模块的耦合
  • 代码部分做了简单的修改
- (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget
{
    NSString *swiftModuleName = params[kCTMediatorParamsKeySwiftTargetModuleName];
    
    // 通用对象获取
    NSString *targetClassString = nil;
    if (swiftModuleName.length > 0) {
        targetClassString = [NSString stringWithFormat:@"%@.Target_%@", swiftModuleName, targetName];
    } else {
        targetClassString = [NSString stringWithFormat:@"Target_%@", targetName];
    }
    // 取缓存的对象
    NSObject *target = self.cachedTarget[targetClassString];
    if (target == nil) {
        Class targetClass = NSClassFromString(targetClassString);
        target = [[targetClass alloc] init];
    }

    // 通用方法获取, Action 的 ‘:’ 在外部手动添加,这样可以支持 无参数方法
    NSString *actionString = [NSString stringWithFormat:@"Action_%@", actionName];
    SEL action = NSSelectorFromString(actionString);
    
    if (target == nil) {
        // 对象不存在,转向 Target_Base 的 Action_NotFoundTarget: 统一处理
        return [self performNoTargetResponseWithTargetString:targetClassString selectorString:actionString originParams:params];
    }
    
    // 按需缓存对象
    if (shouldCacheTarget) {
        self.cachedTarget[targetClassString] = target;
    }
    
    if ([target respondsToSelector:action]) {
        // 正常情况,对象执行方法
        return [self safePerformAction:action target:target params:params];
    } else {
        // 方法不存在,转向 target 的 Action_NotFoundAction: 统一处理
        SEL action = NSSelectorFromString(@"Action_NotFoundAction:");
        if ([target respondsToSelector:action]) {
            return [self performNoActionResponseWithTargetString:targetClassString selectorString:actionString originParams:params];
        } else {
            // 转向 Target_Base 的 Action_NotFoundActionFinal: 统一处理
            [self.cachedTarget removeObjectForKey:targetClassString];
            return [self performNotFoundFinalResponseWithTargetString:targetClassString selectorString:actionString originParams:params];
        }
    }
}

2.2 本地调用简单实践

  • 模块开放接口
#import "Target_Order.h"
#import "CZOrderRootController.h"
#import "CZOrderDetailController.h"

@implementation Target_Order

- (UIViewController *)Action_OrderRootController {
    CZOrderRootController *viewController = [[CZOrderRootController alloc] init];
    return viewController;
}

- (UIViewController *)Action_OrderDetailControllerWithParams:(NSDictionary *)params {
    NSString *aid = params[@"id"];
    CZOrderDetailController *viewController = [[CZOrderDetailController alloc] initWithOrderId:aid];
    return viewController;
}

@end
  • 中间者拓展
// 注意不需要 引用 Target_Order,中间者不依赖模块,但是需要维护相关的 模块名称与方法
#import "CTMediator+CZOrderMediator.h"

@implementation CTMediator (CZOrderMediator)

- (UIViewController *)orderRootController {
    UIViewController *viewController = [self performTarget:@"Order"
                                                    action:@"OrderRootController"
                                                    params:@{}
                                         shouldCacheTarget:NO
                                        ];
    return viewController;
}

- (UIViewController *)orderDetailControllerWithOrderId:(NSString *)orderId {
    UIViewController *viewController = [self performTarget:@"Order"
                                                    action:@"OrderDetailControllerWithParams:"
                                                    params:@{@"id":orderId}
                                         shouldCacheTarget:NO
                                        ];
    return viewController;
}

@end
  • 使用中间者,调用模块
// 引入中间者,不引入对应模块
#import "CTMediator+CZOrderMediator.h"

    UIViewController *controller = [[CTMediator sharedInstance] orderRootController];
    UIViewController *controller = [[CTMediator sharedInstance] orderDetailControllerWithOrderId:@"123"];
    
    [self.navigationController pushViewController:controller animated:YES];

2.3 远程调用简单实践

远程调用本质,是在本地调用基础上,处理远程 URL,解析成可用的本地调用

  • 核心部分,补充了合法远程调用的检查
- (id)performActionWithUrl:(NSURL *)url completion:(void (^)(NSDictionary *))completion
{
    // 解析 URL
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    NSString *urlString = [url query];
    NSString *targetString = url.host;
    NSString *actionName = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
    NSString *actionLocalKey = [NSString stringWithFormat:@"%@_%@", targetString, actionName];
    NSString *actionString = [[Action_RemoteConfig sharedInstance] actions][actionLocalKey];
    for (NSString *param in [urlString componentsSeparatedByString:@"&"]) {
        NSArray *elts = [param componentsSeparatedByString:@"="];
        if([elts count] < 2) continue;
        [params setObject:[elts lastObject] forKey:[elts firstObject]];
    }
    
    id result;
    if (!actionString || ![actionString isKindOfClass:[NSString class]]) {
        // 非法远程调用
        result = [self performNotFoundFinalResponseWithTargetString:targetString selectorString:actionName originParams:params];
    } else {
        // 修正 actionString,处理远程调用
        result = [self performTarget:url.host action:actionString params:params shouldCacheTarget:NO];
    }
    if (completion) {
        if (result) {
            completion(@{@"result":result});
        } else {
            completion(nil);
        }
    }
    return result;
}
  • 使用与本地调用类似
    UIViewController *controller = [[CTMediator sharedInstance] performActionWithUrl:[NSURL URLWithString:@"cz://Order/OPEN_API/OrderDetailControllerWithParams:?id=123"] completion:^(NSDictionary *info) {
        
    }];
    [self.navigationController pushViewController:controller animated:YES];

三、整理

业务模块:需要整理出一份统一的开发接口,供外部调用
中间者:可以独立成一个模块单独维护,统一处理开放接口
基础模块:各种组件、网络、拓展等

开发时各个模块独立,单独运行,减少无关编译,提高效率
整合时,使用 pod 升级,完整编译

你可能感兴趣的:(组件化开发实践)