前言
一直在做一線的業務開發工作,每天接觸業務線,時間久了就開始思考如何能優化架構、提高維護效率,于是就接觸了MVVM
。
MVVM的出現主要是為了解決在開發過程中Controller越來越龐大的問題,變得難以維護,所以MVVM把數據加工的任務從Controller中解放了出來,使得Controller只需要專注于具體業務的工作,ViewModel則去負責數據加工并通過各種通知機制讓View響應ViewModel的改變。
還有一個讓人很容易忽略的問題,大部分國內外資料闡述MVVM的時候都是這樣排布的:Model - View - ViewModel ,
客觀上造成了MVVM不需要Controller的錯覺,可事實上是這樣的么?
分析使用邏輯
ViewModel部分
我最開始聽說MVVM的時候是一臉懵逼的,因為我在這幾個子母中間沒有看到Controller的影子,我對于Controller的使用邏輯一無所知。但是直覺告訴我,Controller依然還是不可獲取的一部分,至少操作View的時候還是會需要。ViewModel這個單詞本身也讓我產生了困擾,這個術語本身可能導致混亂,因為它是我們已經知道的兩個術語的混搭,不知道這個結構更偏向于View和Model哪一邊。
當我查閱資料的時候,網上大部分的MVVM的表述都是View <-> ViewModel <-> Model
,都是在說ViewModel支持數據的雙向綁定,表述模糊,我還是不能完全明白ViewModel
的真正用處和存在意義。
比如像下面的說法:
它將model信息轉變為view需要的信息,同時還將命令從view傳遞到model。View與Model通過ViewModel實現雙向綁定。
我的著眼點放在了上面的第一句話上,即“它將model信息轉變為view信息,同時還將命令從view傳遞到model
”。當我進一步去理解ViewModel的作用的時候,我發現ViewModel更應該被稱呼作為“View與Model中間的觀察協調器”,它主要作用是拿到原始的數據,根據具體業務邏輯需要進行處理,之后將處理好的東西塞到View中去,其職責之一是靜態模型,表示View顯示自身所需的數據,這使View具有更清晰定義的任務,即呈現視圖模型提供的數據,總結為一句話就是與View直接對應的Model,邏輯上是屬于Model層。
Controller部分
那么Controller的作用呢?
MVVM其實是是基于胖Model的架構思路建立的,然后在胖Model中拆出兩部分:Model和ViewModel。
即MVC -> 胖Model -> Model+ ViewModel
這個演化過程。
和上文分析一致,ViewModel本質上算是Model層(作為與View顯示自己所直接對應的Model),所以View并不適合直接持有ViewModel,反之則可以。因為ViewModel有可能并不是一定只服務于特定的一個View,使用更加松散的綁定關系能夠降低ViewModel和View之間的耦合度。現在可以說,Controller唯一關注的是使用來自ViewModel的數據配置和管理各種View,Controller的作用就是負責控制View和ViewModel的綁定和調用關系,Controller不需要了解Web服務調用,Core Data,model對象等,這些都是可以丟給ViewModel去操作。
以下2張圖或許有更直觀的感受:
圖片來源:http://www.sprynthesis.com/2014/12/06/reactivecocoa-mvvm-introduction/
我來解釋一下圖片指代的意思:
- MVVM中的View本質上代指的是View和Controller兩部分結構。
- 而MVVM中的ViewModel則是抽離了Controller的一些業務出來組成了ViewModel,同時Controller的工作量減小了很多。
- 當Controller抽離出來ViewModel之后,MVVM中View也可以區分為View和Controller兩部分之后,就成了第二張圖MVCVM的結構,Controller的代銷也就變小了。
所以說,歸根結底MVVM更應該被形容為View <-> C <-> ViewModel <-> Model
,即MVCVM的設計模式,這樣就很清晰的解釋了Controller的位置以及作用。
進一步梳理
通過以上,我們可以邏輯上得出,Controller應該是持有了ViewModel和View,并對二者進行判斷和匹配操作。ViewModel有可能并不是一定只服務于特定的一個View,Controller當中也會有很多的View,所以,同一個Controller可能持有很多個ViewModel,以此來實現不同的業務邏輯控制多重的View。
Controller唯一關注的是使用來自ViewModel的數據配置和管理各種View,并讓ViewModel知道何時發生需要更改上游數據的相關用戶輸入。 Controller不需要知道網絡請求、數據庫操作以及Model等,這樣就讓Controller更集中的去處理具體的業務邏輯。
圖片來源:http://www.sprynthesis.com/2014/12/06/reactivecocoa-mvvm-introduction/
- Controller:負責View和ViewModel之間的調配和綁定關系,執行業務邏輯。
- View:展示UI,接受Action。
- ViewModel:網絡請求,數據加工,數據持有。
- Model:原始數據。
大致會形成以下調用關系:
代碼演示
廢話不多說,先上Demo:https://github.com/derekhuangxu/HXMVVMDemo
下面我會摘出部分重要代碼,給大家講解一下具體的邏輯
MarshalModel
MarshalModel.h
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger lessonCount;
Model相對來說就比較簡單了,用來儲存原始數據。
MarshalViewModel
MarshalViewModel.h
@interface MarshalViewModel : NSObject
@property (nonatomic, strong, readonly) NSString *name;
@property (nonatomic, strong, readonly) NSString *detailTextString;
@property (nonatomic, assign, readonly) UITableViewCellAccessoryType cellType;
- (instancetype)initWithModel:(MarshalModel *)model;
@end
MarshalViewModel.m
@interface MarshalViewModel ()
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *detailTextString;
@property (nonatomic, assign) UITableViewCellAccessoryType cellType;
@end
@implementation MarshalViewModel
//依賴注入
- (instancetype)initWithModel:(MarshalModel *)model ; {
if (self = [super init]) {
self.name = model.name;
if (model.lessonCount > 35) {
self.detailTextString = @"多于30門課程";
self.cellType = UITableViewCellAccessoryDetailDisclosureButton;
} else {
self.detailTextString = [NSString stringWithFormat:@"課程數量:%ld", (long)model.lessonCount];
self.cellType = UITableViewCellAccessoryNone;
}
}
return self;
}
- ViewModel的.h文件中,只放置了初始化的代碼,執行Model數據的注入,另外提供了向View暴露的接口,這部分要注意了,要加上
readonly
的標示符,當然也可以用GET
方法代替,這樣可以避免View修改ViewModel中的數據,保證數據從一條線注入,處理之后,從另一條線取出。 - ViewModel的.m文件,可以說是對于原始數據的處理操作,這里基本上就是對于原始數據轉化為View需要數據的處理。當然,大家也可以根據自己的需要增加Cache或者數據庫等的操作,也可以增加網絡數據獲取的操作。
MarshalCell
MarshalCell.h
@interface MarshalCell : UITableViewCell
@property (nonatomic, strong) MarshalViewModel *viewModel;
@end
MarshalCell.m
- (void)setViewModel:(MarshalViewModel *)viewModel {
_viewModel = viewModel;
self.textLabel.text = viewModel.name;
self.detailTextLabel.text = viewModel.detailTextString;
self.accessoryType = viewModel.cellType;
}
我只把.m文件中的SET
方法給大家展示出來了,我覺得就可以說明問題,ViewModel中提供了View需要的一切處理好的關鍵要素,那么View就會變得非常扁平,只需要處理點擊這種的Action事件,并且傳遞給Controller即可,不需要關注原始數據轉換的具體業務邏輯。
HomeViewController
HomeViewController.m
@interface HomeViewController ()
@property (nonatomic, strong) NSMutableArray <MarshalViewModel *>*viewModels;
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MarshalCell *cell = [[MarshalCell alloc] initWithStyle: UITableViewCellStyleSubtitle
reuseIdentifier: kMarshalCellIdentifier];
cell.viewModel = self.viewModels[indexPath.row];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.viewModels.count;
}
- (void)getData {
[[MarshalService shareInstance]fetchDataCompletion:^(NSArray<MarshalModel *> * _Nonnull data) {
self.viewModels = [self viewModelsWithDatas:[data mutableCopy]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
} failure:^(NSError * _Nonnull error) {
NSLog(@"Failed to fetch courses:%@", error);
}];
}
大家可以看到,我用了數組來儲存的ViewModel,原因是因為每個Cell所對應的的數據不一致導致UI展示不一致,所以每個Cell要有一個自己的ViewModel來填充自己UI數據。這就進一步印證了上面說的,ViewModel本質仍然是Model層。
疑問點(不定期更新)
1、為什么View沒有.h接口的可讀處理,而ViewModel中要有?
在ViewModel中數據單向注入,之后會有數據根據業務邏輯處理,之后向View提供數據接口,為了保證數據不會被污染,所以增加了`readonly`的標示符,而View中則不需要以上的邏輯。
2、當點擊某個Cell的某部分之后,如何向后傳值?
1.Controller找到對應的ViewModel,ViewModel作為Mother ViewModel,替代Controller做一個臟活,去生成相對應的Child ViewModel。
2.ViewModel將Child ViewModel返回給Controller。
3.Controller利用Child ViewModel生成下一頁面的Controller,執行跳轉操作。