利用 AOP 模塊化細節業務,確實有趣。由於咱們一般狀況下提及 AOP,都會想起好比「埋點」、「method swizzing」等字眼,角度比較宏觀,起到了解耦的做用;本文從另外一個角度出發,使用 AOP 思想對細節業務作模塊分離的工做。git
AOP簡介 面向切面編程(也叫面向方面):Aspect Oriented Programming(AOP),是目前軟件開發中的一個熱點。利用AOP能夠對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度下降,提升程序的可重用性,同時提升了開發的效率。面試
主要的功能是:日誌記錄,性能統計,安全控制,事務處理,異常處理等等。算法
在實際業務需求中,出場率很高的是UITalbeView和UICollecitonView等須要用大量代理方法配置的視圖,固然這是蘋果程序設計的慣例。當UI界面很複雜,業務邏輯至關多的時候,雖然把網絡請求、數據處理、視圖封裝等都模塊分離出去了,可是配置代理裏面的邏輯太多,咱們想要每個類處理一部分代理方法。編程
@implementation TestTableViewDigitConfig
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 80;
}
@end
複製代碼
@implementation TestTableViewClickConfig
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"click -- section:%ld, row:%ld", indexPath.section, indexPath.row);
}
@end
複製代碼
@implementation TestTableViewCellConfig
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class)];
if (!cell) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass(UITableViewCell.class)];
}
cell.textLabel.text = [NSString stringWithFormat:@"第%ld行", indexPath.row];
return cell;
}
@end
複製代碼
如代碼所見,這裏將 tableView 的代理用三個類來分別實現,而後在 UIViewController 裏面只須要寫這些代碼:swift
@interface TestVC ()
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) YBAOPManager *aopManager;
@property (nonatomic, strong) TestTableViewDigitConfig *digitConfig;
@property (nonatomic, strong) TestTableViewClickConfig *clickConfig;
@property (nonatomic, strong) TestTableViewCellConfig *cellConfig;
@end
@implementation TestVC
#pragma mark life cycle
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.tableView];
}
#pragma mark getter
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
_tableView.tableFooterView = [UIView new];
_digitConfig = [TestTableViewDigitConfig new];
_clickConfig = [TestTableViewClickConfig new];
_cellConfig = [TestTableViewCellConfig new];
_aopManager = [YBAOPManager new];
[_aopManager addTarget:_digitConfig];
[_aopManager addTarget:_clickConfig];
[_aopManager addTarget:_cellConfig];
_tableView.delegate = _aopManager;
_tableView.dataSource = _aopManager;
}
return _tableView;
}
@end
複製代碼
核心代碼就是將 YBAOPManager 類的使用:設計模式
當你須要使用多個對象(target)來承接一些方法的實現,初始化 YBAOPManager 實例,將這些對象實例添加到 YBAOPManager 實例中(addTarget),最後將 YBAOPManager 實例做爲這些方法的第一承接者。剩下的方法分發工做就交給該類了。安全
給你們推薦一個iOS技術交流羣!763164022羣內提供數據結構與算法、底層進階、swift、逆向、底層面試題整合文檔等免費資料!bash