何為架構?
架構指的是開發中的設計方案。類與類之間的關系,模塊與模塊之間的關系,客戶端與服務器的關系等等都可稱之為架構的一部分。
我們在iOS開發過程中經常聽到的架構有:
MVC、MVP、MVVP、VIPER、CDD
也有另外一種架構的說法:
三層架構、四層架構
一、MVC的理解
蘋果官方給出的關于MVC的理解是:Model-View-Controller
MVC是模型、視圖、控制開發模式,對于iOS SDK,所有的View都是視圖層,它應該獨立于模型層,由視圖控制層來控制。所有的用戶數據都是模型層,它應該獨立于視圖。所有的ViewController都是控制層,由它負責控制視圖,訪問模型數據。
MVC通訊規則:
1、Controller ->Model:單向通信,Controller需要將Model呈現給用戶,因此需要知道模型的一切,還需要有同Model完全通信的能力,并且能任意使用Model的API。
2、Controller ->View:單向通信,Ccontroller通過View來布局用戶界面。
3、Model ->View:永遠不要直接通信,Model是獨立于UI的,并不需要和View直接通信,View通過Controller獲取Model數據。
看如下代碼:
創建一個名為News的模型
News.h
#import <Foundation/Foundation.h>
@interface News : NSObject
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *content;
@end
News.m
#import "News.h"
@implementation News
@end
NewsViewController.h
#import <UIKit/UIKit.h>
@interface NewsViewController : UITableViewController
@end
NewsViewController.m
#import "NewsViewController.h"
#import "News.h"
@interface NewsViewController ()
@property (strong, nonatomic) NSMutableArray *newsData;
@property (strong, nonatomic) NSMutableArray *shopData;
@end
@implementation NewsViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self loadNewsData];
}
//模擬加載model數據,在實際開發中應該是通過網絡加載或者獲取緩存中的模型數據
- (void)loadNewsData
{
self.newsData = [NSMutableArray array];
for (int i = 0; i < 20; i++) {
News *news = [[News alloc] init];
news.title = [NSString stringWithFormat:@"news-title-%d", i];
news.content = [NSString stringWithFormat:@"news-content-%d", i];
[self.newsData addObject:news];
}
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.newsData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
News *news = self.newsData[indexPath.row];
cell.detailTextLabel.text = news.price;
cell.textLabel.text = shop.name;
return cell;
}
@end
通過上述代碼和運行結果可以看到,Model是News,Controller是NewViewController ,View是tableView(包含在Controller中,這是一個tableViewController)。
現在MVC三元素已經有了,細看一下它的具體實現。
1、controller確實是擁有了News這個model,并在controller中創建加載這個模型的數據。
2、controller也擁有了view,這個view就是內置的tableView。
3、view中并沒有擁有News這個model,這兩者并沒有直接通訊,兩者并不知道彼此的存在。
4、view之所以顯示模型數據,是因為Controller把model里面的每一個屬性都拿出來賦值到view中的。
MVC模型的優點:
1、因為Model和View沒有直接聯系,互相不知道對方的存在,所以低耦合性,有利于開發分工,有利于組件重用,可維護性高。
缺點:
1、Controller的代碼過于臃腫,因為它需要連接Model和View的通訊。
二、MVC的變種
看如下代碼:
創建一個名為APP的model
App.h
#import <Foundation/Foundation.h>
@interface App : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *image;
@end
App.m
#import "App.h"
@implementation App
@end
創建一個APPView.h
#import <UIKit/UIKit.h>
@class App, AppView;
@protocol AppViewDelegate <NSObject>
@optional
- (void)appViewDidClick:(AppView *)appView;
@end
@interface AppView : UIView
@property (strong, nonatomic) App *app;
@property (weak, nonatomic) id<AppViewDelegate> delegate;
@end
APPView.m
#import "AppView.h"
#import "App.h"
@interface AppView()
@property (weak, nonatomic) UIImageView *iconView;
@property (weak, nonatomic) UILabel *nameLabel;
@end
@implementation AppView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
UIImageView *iconView = [[UIImageView alloc] init];
iconView.frame = CGRectMake(0, 0, 100, 100);
[self addSubview:iconView];
_iconView = iconView;
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.frame = CGRectMake(0, 100, 100, 30);
nameLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:nameLabel];
_nameLabel = nameLabel;
}
return self;
}
- (void)setApp:(App *)app
{
_app = app;
self.iconView.image = [UIImage imageNamed:app.image];
self.nameLabel.text = app.name;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(appViewDidClick:)]) {
[self.delegate appViewDidClick:self];
}
}
@end
ViewController.m
#import "ViewController.h"
#import "App.h"
#import "AppView.h"
@interface ViewController () <AppViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 創建view
AppView *appView = [[AppView alloc] init];
appView.frame = CGRectMake(100, 100, 100, 150);
appView.delegate = self;
[self.view addSubview:appView];
// 加載模型數據
App *app = [[App alloc] init];
app.name = @"QQ";
app.image = @"QQ";
// 設置數據到view上
appView.app = app;
}
#pragma mark - AppViewDelegate
- (void)appViewDidClick:(AppView *)appView
{
NSLog(@"控制器監聽到了appView的點擊");
}
@end
通過上述代碼可以看出:
1、model作為一個對象被添加到view中,model中的數據在創建model的時候被使用。
2、view中的控件被隱藏,外界不知道view內部的結構。
3、對controller進行了瘦身,在controller中只需要傳入model對象給view即可。
優點:對Controller進行瘦身,將view內部的細節封裝起來,外界不知道view內部的具體實現。
缺點:view依賴于model。
三、MVP
Model-View-Presenter(主持者):跟MVC模型類似,只不過是用Presenter代替了Controller來對model和view進行調度。
看如下代碼:
APP和APPView代碼跟上面代碼一致,我們此時需要增加一個AppPresenter文件
AppPresenter.h
#import <UIKit/UIKit.h>
@interface AppPresenter : NSObject
- (instancetype)initWithController:(UIViewController *)controller;
@end
AppPresenter.m
#import "AppPresenter.h"
#import "App.h"
#import "AppView.h"
@interface AppPresenter() <AppViewDelegate>
@property (weak, nonatomic) UIViewController *controller;
@end
@implementation AppPresenter
- (instancetype)initWithController:(UIViewController *)controller
{
if (self = [super init]) {
self.controller = controller;
// 創建View
AppView *appView = [[AppView alloc] init];
appView.frame = CGRectMake(100, 100, 100, 150);
appView.delegate = self;
[controller.view addSubview:appView];
// 加載模型數據
App *app = [[App alloc] init];
app.name = @"QQ";
app.image = @"QQ";
// 賦值數據
[appView setName:app.name andImage:app.image];
}
return self;
}
#pragma mark - AppViewDelegate
- (void)appViewDidClick:(AppView *)appView
{
NSLog(@"presenter 監聽了 appView 的點擊");
}
@end
ViewController.m
#import "ViewController.h"
#import "AppPresenter.h"
@interface ViewController ()
@property (strong, nonatomic) AppPresenter *presenter;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.presenter = [[AppPresenter alloc] initWithController:self];
}
@end
通過上述代碼可以看出:
1.通過一個Presenter的中間媒介把原來在controller中的邏輯放在自己的實現方法里。
2.如果controller中需要不同的模塊,可以創建多個Presenter來實現。比如想在controller中增加兩個view,可以創建兩個Presenter實現這兩個view的實現。
四、MVVM
概念:MVVM是model-view-viewModel的縮寫,它是一種基于前端開發的架構模式,核心是提供對view和ViewModel的雙向數據綁定,這使得ViewModel的狀態改變可以自動傳遞給View,即所謂的數據雙向綁定。在H5還未流行的時候MVC作為web的最佳實踐是OK的,因為Web應用的View相對來說比較簡單,前端所需的數據在后端基本上都可以處理好,View層主要是做展示,用Controller來處理復雜的業務邏輯。所以View層相對來說比較輕量,就是所謂的瘦客戶端思想。
看如下代碼:
News.h
#import <Foundation/Foundation.h>
@interface News : NSObject
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *content;
@end
News.m
@implementation News
@end
NewsViewModel.h
#import <Foundation/Foundation.h>
@interface NewsViewModel : NSObject
-(void)loadNewsData:(void (^)(NSArray *newsDdata))completion;
@end
NewsViewModel.m
#import "NewsViewModel.h"
#import "News.h"
@implementation NewsViewModel
//通常在此處發送網絡請求獲取數據,實現數據轉字典模型等操作
-(void)loadNewsData:(void (^)(NSArray *))completion
{
if (!completion) return;
NSMutableArray *newsData = [NSMutableArray array];
for (int i = 0; i < 20; i++) {
News *news = [[News alloc] init];
news.title = [NSString stringWithFormat:@"news-title-%d", i];
news.content = [NSString stringWithFormat:@"news-content-%d", i];
[newsData addObject:news];
}
completion(newsData);
}
@end
NewsViewController.m
#import "NewsViewController.h"
#import "News.h"
#import "NewsViewModel.h"
@interface NewsViewController ()
@property (strong, nonatomic) NSMutableArray *newsData;
@property (strong, nonatomic) NewsViewModel *newsVM;
@end
@implementation NewsViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.newsVM = [[NewsViewModel alloc] init];
[self.newsVM loadNewsData:^(NSArray *newsDdata) {
self.newsData = newsDdata;
}];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.newsData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
MJNews *news = self.newsData[indexPath.row];
cell.detailTextLabel.text = news.content;
cell.textLabel.text = news.title;
return cell;
}
通過上訴代碼可以知道:
1、viewModel中發送網絡請求、實現字典轉模型操作。
2、在Controller中獲取viewModel的值,然后將數據傳遞給view顯示。
五、MVVM變種
基于上面MVC變種,我們可以仿照它實現MVVM的變種。
看如下代碼:
App.h
import <Foundation/Foundation.h>
@interface App : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *image;
@end
App.m
#import "App.h"
@implementation App
@end
AppView.h
#import <UIKit/UIKit.h>
@class AppView, AppViewModel;
@protocol AppViewDelegate <NSObject>
@optional
- (void)appViewDidClick:(AppView *)appView;
@end
@interface AppView : UIView
@property (weak, nonatomic) AppViewModel *viewModel;
@property (weak, nonatomic) id<AppViewDelegate> delegate;
@end
AppView.m
#import "AppView.h"
#import "NSObject+FBKVOController.h"
@interface AppView()
@property (weak, nonatomic) UIImageView *iconView;
@property (weak, nonatomic) UILabel *nameLabel;
@end
@implementation AppView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
UIImageView *iconView = [[UIImageView alloc] init];
iconView.frame = CGRectMake(0, 0, 100, 100);
[self addSubview:iconView];
_iconView = iconView;
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.frame = CGRectMake(0, 100, 100, 30);
nameLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:nameLabel];
_nameLabel = nameLabel;
}
return self;
}
- (void)setViewModel:(AppViewModel *)viewModel
{
_viewModel = viewModel;
__weak typeof(self) waekSelf = self;
[self.KVOController observe:viewModel keyPath:@"name" options:NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
waekSelf.nameLabel.text = change[NSKeyValueChangeNewKey];
}];
[self.KVOController observe:viewModel keyPath:@"image" options:NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
waekSelf.iconView.image = [UIImage imageNamed:change[NSKeyValueChangeNewKey]];
}];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if ([self.delegate respondsToSelector:@selector(appViewDidClick:)]) {
[self.delegate appViewDidClick:self];
}
}
@end
AppViewModel.h
#import <UIKit/UIKit.h>
@interface AppViewModel : NSObject
- (instancetype)initWithController:(UIViewController *)controller;
@end
AppViewModel.m
#import "AppViewModel.h"
#import "App.h"
#import "AppView.h"
@interface AppViewModel() <AppViewDelegate>
@property (weak, nonatomic) UIViewController *controller;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *image;
@end
@implementation AppViewModel
- (instancetype)initWithController:(UIViewController *)controller
{
if (self = [super init]) {
self.controller = controller;
// 創建View
AppView *appView = [[AppView alloc] init];
appView.frame = CGRectMake(100, 100, 100, 150);
appView.delegate = self;
appView.viewModel = self;
[controller.view addSubview:appView];
// 加載模型數據
App *app = [[App alloc] init];
app.name = @"QQ";
app.image = @"QQ";
// 設置數據
self.name = app.name;
self.image = app.image;
}
return self;
}
#pragma mark - AppViewDelegate
- (void)appViewDidClick:(AppView *)appView
{
NSLog(@"viewModel 監聽了 appView 的點擊");
}
@end
ViewController.m
#import "ViewController.h"
#import "AppViewModel.h"
@interface ViewController ()
@property (strong, nonatomic) AppViewModel *viewModel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.viewModel = [[AppViewModel alloc] initWithController:self];
}
@end
通過上述代碼可以得知:
1、把view放到viewModel中而不是controller中。這樣讓controller持有viewModel即可。
2、在viewmodel中對數據進行處理,如發送網絡請求、字典轉模型。把得到的數據傳遞到view中。
六、MVC和MVVM的區別:
最大的區別是:實現了View和Model的自動更新,也就是說當model的屬性發生改變時,我們不再手動的操作,通過viewModel來處理數據的業務邏輯,這種低耦合模式提高代碼的可重用性。
總的來說MVVM比MVC精簡很多,一定程度上簡化了界面與業務的依賴性,也解決了數據的頻繁更新問題。對于這兩種模式,可能比較復雜的情況下分不清Model和View,但是在實際開發中大可不必糾結。只要掌握了架構的思想,針對不同的業務情況,選擇最適合的架構來解決問題即可。
七、三層架構和四層架構
界面層:一般指的是跟界面顯示有關的層面。
業務層:就是一些點擊事件。
數據層:負責數據庫或者網絡請求獲取的數據。
比如實現一個新聞列表的功能。新聞列表界面(即tableView)就是界面層,加載新聞數這一功能就是業務層,而數據的來源則是數據層。
與三層架構不同的是多了一個網絡層,這樣更加精細的分工可以把網絡請求和數據層實現分離。