最初在網(wǎng)上看到相關(guān)內(nèi)容,是蘑菇街組件化相關(guān)討論。(Limboy(文章1 文章2) 和 Casa (文章))。
但是我大家討論的內(nèi)容應(yīng)該是如何解耦吧,而不是組件化本身,只不過解耦是組件化的前提而已。
我現(xiàn)在理解的有兩種方案:
一、中間件+runtime
//Mediator.m
@implementation Mediator
+ (UIViewController *)BookDetailComponent_viewController:(NSString *)bookId {
Class cls = NSClassFromString(@"BookDetailComponent");
return [cls performSelector:NSSelectorFromString(@"detailViewController:") withObject:@{@"bookId":bookId}];
}
+ (UIViewController *)ReviewComponent_viewController:(NSString *)bookId type:(NSInteger)type {
Class cls = NSClassFromString(@"ReviewComponent");
return [cls performSelector:NSSelectorFromString(@"reviewViewController:") withObject:@{@"bookId":bookId, @"type": @(type)}];
}
@end
當(dāng)然直接這樣寫,組件(模塊)多了以后,這個中間件將會變的異常龐大,所以可以通過category方式分離組件接口代碼。這里有個文章具體講解了細(xì)節(jié)實現(xiàn),增加了通過 target-action 簡化寫法。
二、URL+Block
中間件提供方法,可以將url和block進(jìn)行綁定,各組件都要首先調(diào)用注冊方法,把自己的功能(block)和對應(yīng)的url注冊到中間件中,才能讓其他組件通過url調(diào)用。
一個簡化的實現(xiàn):
//Mediator.m 中間件
@implementation Mediator
typedef void (^componentBlock) (id param);
@property (nonatomic, storng) NSMutableDictionary *cache
- (void)registerURLPattern:(NSString *)urlPattern toHandler:(componentBlock)blk {
[cache setObject:blk forKey:urlPattern];
}
- (void)openURL:(NSString *)url withParam:(id)param {
componentBlock blk = [cache objectForKey:url];
if (blk) blk(param);
}
@end
//BookDetailComponent 組件
#import "Mediator.h"
#import "WRBookDetailViewController.h"
+ (void)initComponent {
[[Mediator sharedInstance] registerURLPattern:@"weread://bookDetail" toHandler:^(NSDictionary *param) {
WRBookDetailViewController *detailVC = [[WRBookDetailViewController alloc] initWithBookId:param[@"bookId"]];
[[UIApplication sharedApplication].keyWindow.rootViewController.navigationController pushViewController:detailVC animated:YES];
}];
}
//WRReadingViewController.m 調(diào)用者
//ReadingViewController.m
#import "Mediator.h"
+ (void)gotoDetail:(NSString *)bookId {
[[Mediator sharedInstance] openURL:@"weread://bookDetail" withParam:@{@"bookId": bookId}];
}
方案2最大的問題就是每個組件都需要初始化,內(nèi)存里需要保存一份表,組件多了會有內(nèi)存問題。
參考:iOS 組件化方案探索