我对这两种能力有点困惑。两种方法都可以实现相同的功能吗?如果我可以使用运行时参数调用程序集并吐出完全注入的对象图,为什么要创建协议并允许台风自动生成实现?
在我看来,带有运行时参数的程序集应该是首选方法。有了这个,如果我有多个需要注入的依赖项,我就不必创建大型、冗长的构造函数。
例如我可以这样定义一个工厂:
@protocol AWDailyDetailsPagingViewControllerFactory <NSObject>
@property (nonatomic, strong, readonly) AWStripViewController *stripViewController;
@property (nonatomic, strong, readonly) AWDailyDetailsDataSource *dailyDetailsDataSource;
@property (nonatomic, strong, readonly) AWLocationListViewController *locationListViewController;
@property (nonatomic, strong, readonly) id<AWPresentationController> presentationController;
@property (nonatomic, strong, readonly) AWPullToRefreshGestureHandler *pullToRefreshGestureHandler;
- (AWDailyDetailsPagingViewController *)dailyDetailsPagingViewControllerWithUserLocation:(AWUserLocation *)userLocation initialLayoutModel:(AWDailyDetailsViewControllerLayoutModel *)initialLayoutModel;
@end
然后我需要在我的 ViewController 中创建一个构造函数,如下所示:
- (instancetype)initWithStripViewController:(AWStripViewController *)stripViewController
dailyDetailsDataSource:(AWDailyDetailsDataSource *)dailyDetailsDataSource
locationListViewController:(AWLocationListViewController *)locationListViewController
presentationController:(id<AWPresentationController>)presentationController
pullToRefreshGestureHandler:(AWPullToRefreshGestureHandler *)pullToRefreshGestureHandler
userLocation:(AWUserLocation *)userLocation
initialLayoutModel:(AWDailyDetailsViewControllerLayoutModel *)initialLayoutModel;
使用这个工厂协议是超级干净和优雅的,所以没有问题:
[self.dailyDetailsPagingViewControllerFactory dailyDetailsPagingViewControllerWithUserLocation:userLocation initialLayoutModel:initialLayoutModel];
但是男孩那个构造函数有点丑陋。在我看来,使用运行时参数和程序集,我可以通过注入属性(无论如何我已经定义)来避免该构造函数。例如,我相信我的程序集看起来像这样:
- (id)dailyDetailsPagingViewControllerWithUserLocation:(AWUserLocation *)userLocation initialLayoutModel:(AWDailyDetailsViewControllerLayoutModel *)layoutModel {
return [TyphoonDefinition withClass:[AWDailyDetailsPagingViewController class] configuration:^(TyphoonDefinition* definition) {
[definition injectProperty:@selector(stripViewController) with:[self horizontalStripViewController]];
[definition injectProperty:@selector(dailyDetailsDataSource) with:[self dailyDetailsDataSource]];
[definition injectProperty:@selector(locationListViewController) with:[self.navigationAssembly locationListViewController]];
[definition injectProperty:@selector(pullToRefreshGestureHandler) with:[self.navigationAssembly pullToRefreshGestureHandler]];
[definition injectProperty:@selector(presentationController) with:[self.navigationAssembly presentationController]];
[definition injectProperty:@selector(userLocation) with:userLocation];
[definition injectProperty:@selector(layoutModel) with:layoutModel];
}];
}
现在所有内容都包含在程序集中,在运行时我应该看到与 Factory Provider 相同的结果。
那么我在正确的轨道上吗?这两个功能是否提供相同的功能?大多数情况下应该使用哪一种?有关系吗?
感谢您的任何评论和回答!