MVC、MVP、MVV

何為架構?
架構指的是開發中的設計方案。類與類之間的關系,模塊與模塊之間的關系,客戶端與服務器的關系等等都可稱之為架構的一部分。
我們在iOS開發過程中經常聽到的架構有:
MVC、MVP、MVVP、VIPER、CDD
也有另外一種架構的說法:
三層架構、四層架構

一、MVC的理解
蘋果官方給出的關于MVC的理解是:Model-View-Controller

image

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

image

通過上述代碼和運行結果可以看到,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

image

通過上述代碼可以看出:
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,但是在實際開發中大可不必糾結。只要掌握了架構的思想,針對不同的業務情況,選擇最適合的架構來解決問題即可。

七、三層架構和四層架構

image

界面層:一般指的是跟界面顯示有關的層面。
業務層:就是一些點擊事件。
數據層:負責數據庫或者網絡請求獲取的數據。
比如實現一個新聞列表的功能。新聞列表界面(即tableView)就是界面層,加載新聞數這一功能就是業務層,而數據的來源則是數據層。

image

與三層架構不同的是多了一個網絡層,這樣更加精細的分工可以把網絡請求和數據層實現分離。

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,488評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,034評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,327評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,554評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,337評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,883評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,975評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,114評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,625評論 1 332
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,555評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,737評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,244評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,973評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,615評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,343評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,699評論 2 370

推薦閱讀更多精彩內容