谈谈我对MVC、MVP、MVVM架构的认识

【原创博文,转载请注明出处!】

根据在项目开发中的长期积累和学习,本文所涉及的三种设计架构,我都会通过Objective-C语言在iOS开发环境下给出可运行demo👉Github demo地址。

<一>、MVC

MVC架构在iOS开发中有两种形式的体现:

  • 1 、Apple 版本的MVC
  • 2、变种的MVC(iOS开发中常见)
A. 首先我们看一下Apple版本的MVC 中,M、V、C三个模块之间的关系图:
Apple 版本的MVC.png

上图可见:Apple版本的MVC中,Model和View是完全隔绝的。Model与View之间通过Controller作为桥梁进行沟通。
图中四个指向箭头的关系解释如下:
a. Controller同时指向Model和View表明Controller拥有Model和View;
b. Model指向Controller,意味着Model数据的改变需要通知到Controller,由Controller来刷新View的显示状态;
c. View指向Controller,View里面的事件需要通知到控制器去处理(如:Block、代理、通知)。
这种形式的MVC被UITableView发挥得淋漓尽致,举个例子:

Apple 版本的MVC.png
// Student.h文件
@interface Student : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *price;
@end


// StudentViewController.m文件
#import "StudentViewController.h"
#import "Student.h"

@interface StudentViewController ()
@property (strong, nonatomic) NSMutableArray *newsData;
@property (strong, nonatomic) NSMutableArray *studentData;
@end

@implementation StudentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadStudent];
}

- (void)loadStudent
{
    self.studentData = [NSMutableArray array];
    
    for (int i = 0; i < 20; i++) {
        Student *student = [[Student alloc] init];
        student.name = [NSString stringWithFormat:@"姓名-%d", I];
        student.price = [NSString stringWithFormat:@"学号:%d", I];
        [self.studentData addObject:student];
    }
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.studentData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
    Student *student = self.studentData[indexPath.row];
    cell.detailTextLabel.text = student.price;
    cell.textLabel.text = student.name;
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"1111");
}
@end

这种MVC,view与model完全隔离,view不依赖model,所以优点是:view和model可以重复利用,也可以单独使用。

再来看看缺点(下图红框所示):

Apple版本MVC缺点.png

缺点:model数据需要在Controller中加载,另外view上面的控件赋值也需要逐一在控制器中赋值,所以控制器中代码很臃肿。

B. 让我们再来看一下项目中常见的变种MVC 中,M、V、C三个模块之间的关系图:
变种的MVC.png
此图适用于下文讲到的MVC、MVP、MVVP.png

这种MVC,View拥有Model(Model通常作为View的一个实例对象),所以View能第一时间知道Model的变化,这样我们就可以将View的内部实现隐蔽起来,也就是无需对外暴露View内部控件API。

// MVCModel.h
#import <Foundation/Foundation.h>

@interface MVCModel : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *imageName;
@end


// MVCView.h
#import <UIKit/UIKit.h>
@class MVCModel, MVCView;

@protocol MVCViewDelegate <NSObject>
@optional
- (void)mvcViewDidClicked:(MVCView *)view;
@end

@interface MVCView : UIView
@property (nonatomic, strong) MVCModel *mvcModel;
@property (nonatomic, weak) id<MVCViewDelegate> delegate;
@end

// MVCView.m
#import "MVCView.h"
#import "MVCModel.h"

@interface MVCView ()
@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, weak) UILabel *label;
@end

@implementation MVCView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 150)];
        [self addSubview:imageView];
        _imageView = imageView;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 100, 60)];
        [self addSubview:label];
        _label = label;
    }
    return self;
}

- (void)setMvcModel:(MVCModel *)mvcModel{
    _mvcModel = mvcModel;
    self.imageView.image = [UIImage imageNamed:@"monkey1.png"];
    self.label.text = mvcModel.name;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([self.delegate respondsToSelector:@selector(mvcViewDidClicked:)]) {
        [self.delegate mvcViewDidClicked:self];
    }
}
@end


// MVCGeneralController.m
#import "MVCGeneralController.h"
#import "MVCModel.h"
#import "MVCView.h"

#define SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)

@interface MVCGeneralController ()<MVCViewDelegate>

@end


@implementation MVCGeneralController

- (void)viewDidLoad {
    [super viewDidLoad];

    MVCView *view = [[MVCView alloc] initWithFrame:CGRectMake(100, 100, 150, 200)];
    view.center = CGPointMake(SCREEN_WIDTH / 2, 300);
    [self.view addSubview:view];
    view.delegate = self;
    
    MVCModel *model = [[MVCModel alloc] init];
    model.name = @"a Monkey";
    model.imageName = @"monkey";
    
    view.mvcModel = model;
}

-(void)mvcViewDidClicked:(MVCView *)view{
    NSLog(@"%s",__func__);
}

@end

通过代码可见,变种的MVC架构下:
优点:相对于Apple的MVC而言,对Controller进行瘦身,将View内部的细节封装起来了,外界不知道View内部的具体实现;
缺点:View依赖于Model。

<二>、MVP
MVP.png

初看上去MVP与Apple版本的MVC很相似,仔细对比发现MVP中的P"取代"了MVC中的C功能,demo如下:

//
//  MVP_ViewController.m
//
//  Created by Rephontil.Zhou on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import "MVP_ViewController.h"
#import "Presenter.h"

@interface MVP_ViewController ()
@property (nonatomic, strong) Presenter *presenter;
@end

@implementation MVP_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.presenter = [[Presenter alloc] initWithController:self];
}

@end


//
//  MVP_Model.h
//
//  Created by Rephontil.Zhou on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.

#import <Foundation/Foundation.h>

@interface MVP_Model : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *imageName;
@end


//
//  MVP_View.h
//
//  Created by Rephontil.Zhou on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import <UIKit/UIKit.h>
@class MVP_View;
@protocol MVP_ViewDelegate <NSObject>

@optional
- (void)viewDidClicked:(MVP_View *)view;
@end

@interface MVP_View : UIView
@property (nonatomic, weak) id<MVP_ViewDelegate> delegate;

- (void)setImageName:(NSString *)imageName introduction:(NSString *)introduction;
@end


//
//  MVP_View.m
//
//  Created by Rephontil.Zhou on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import "MVP_View.h"

@interface MVP_View ()
@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, weak) UILabel *label;
@end

@implementation MVP_View

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 150)];
        [self addSubview:imageView];
        _imageView = imageView;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 100, 60)];
        [self addSubview:label];
        _label = label;
    }
    return self;
}

- (void)setImageName:(NSString *)imageName introduction:(NSString *)introduction{
    self.imageView.image = [UIImage imageNamed:imageName];
    self.label.text = introduction;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([self.delegate respondsToSelector:@selector(viewDidClicked:)]) {
        [self.delegate viewDidClicked:self];
    }
}

@end


//
//  Presenter.h
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface Presenter : NSObject
- (instancetype)initWithController:(UIViewController *)controller;
@end

//
//  Presenter.m
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import "Presenter.h"
#import "MVP_View.h"
#import "MVP_Model.h"

#define SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)

@interface Presenter ()<MVP_ViewDelegate>

@property (nonatomic, weak) UIViewController *controller;
@end

@implementation Presenter

- (instancetype)initWithController:(UIViewController *)controller{
    
    if (self = [super init]) {
        
        self.controller = controller;
        
        MVP_View *view = [[MVP_View alloc] initWithFrame:CGRectMake(100, 100, 150, 200)];
        view.center = CGPointMake(SCREEN_WIDTH / 2, 300);
        [controller.view addSubview:view];
        view.delegate = self;
        
        MVP_Model *model = [[MVP_Model alloc] init];
        model.name = @"a Monkey";
        model.imageName = @"monkey1";
        
        [view setImageName:model.imageName introduction:model.name];
    }
    
    return self;
}

- (void)viewDidClicked:(MVP_View *)view{
    NSLog(@"%s",__func__);
}

@end

MVP架构下,之前控制器C需要负责的任务由Presenter去处理,Presenter可以理解为Controller的一个代理者,如果Controller中有很多复杂的UI,我们可以为这个Controller设计多个Presenter,这样每一部分的数据加载等任务分散到各自的Presenter中处理,Controller看起来非常干净
MVP中,Model与View仍然可以做到绝对的隔离,没有依赖关系,所以Model与VIew也可以单独使用。

<三>、MVVM
MVVM.png

从MVVM关系图中看上去,该架构与MVP架构很像,Model与View之间仍然是隔离的,可以单独使用,灵活性、复用性都很友好。ViewModel与View之间双向绑定,鉴于在iOS环境下的MVVM架构中,一般我们在View中通过监听ViewModel中属性的变化去更新View的显示效果,所以MVVM架构在iOS开发中一般搭配RAC框架使用(或者FB 推出的轻量级"NSObject+FBKVOController"框架)。该架构下:控制器Controller拥有ViewModel,ViewModel同时拥有View和Model,对于复杂的界面,一个Controller可以有多个ViewModel去实现各部分的业务逻辑,我将ViewModel理解为控制器的"代理",同MVP一样,MVVM大大解放了Controller职责,demo源码如下:

//
//  MVVM_ViewController.m
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import "MVVM_ViewController.h"
#import "ViewModel.h"

@interface MVVM_ViewController ()
@property (nonatomic, strong) ViewModel *viewModel;
@end

@implementation MVVM_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.viewModel = [[ViewModel alloc] initWithController:self];
    // Do any additional setup after loading the view.
}

@end


//
//  ViewModel.h
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewModel : NSObject

- (instancetype)initWithController:(UIViewController *)controller;

@end

//
//  ViewModel.m
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import "ViewModel.h"
#import "MVVM_Model.h"
#import "MVVM_View.h"

#define SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)


@interface ViewModel ()<MVVM_ViewDelegate>
@property (weak, nonatomic) UIViewController *controller;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *imageName;
@property (weak, nonatomic) UIView *view;
@end


@implementation ViewModel

- (instancetype)initWithController:(UIViewController *)controller{
    if (self = [super init]) {
        
        self.controller = controller;
        MVVM_View *view = [[MVVM_View alloc] initWithFrame:CGRectMake(100, 100, 150, 200)];
        view.center = CGPointMake(SCREEN_WIDTH / 2, 300);
        [controller.view addSubview:view];
        view.viewModel = self;
        view.delegate = self;
        
        MVVM_Model *model = [[MVVM_Model alloc] init];
        model.name = @"a Monkey";
        model.imageName = @"monkey";
        
        self.name = model.name;
        self.imageName = model.imageName;
    }
    return self;
}

- (void)viewDidClicked:(MVVM_View *)view{
    NSLog(@"%s",__func__);
    
    self.imageName = [self.imageName isEqualToString:@"monkey1"] ? @"monkey" : @"monkey1";
}

@end


//
//  MVVM_View.h
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import <UIKit/UIKit.h>
@class MVVM_View, ViewModel;

@protocol MVVM_ViewDelegate <NSObject>
@optional
- (void)viewDidClicked:(MVVM_View *)view;
@end

@interface MVVM_View : UIView
@property (nonatomic, weak) ViewModel *viewModel;
@property (nonatomic, weak) id<MVVM_ViewDelegate> delegate;
@end

//
//  MVVM_View.m
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import "MVVM_View.h"
#import "NSObject+FBKVOController.h"

@interface MVVM_View ()
@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, weak) UILabel *label;
@end


@implementation MVVM_View

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 150)];
        [self addSubview:imageView];
        _imageView = imageView;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 100, 60)];
        [self addSubview:label];
        _label = label;
    }
    return self;
}

- (void)setViewModel:(ViewModel *)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.label.text = change[NSKeyValueChangeNewKey];
    }];
    
    [self.KVOController observe:viewModel keyPath:@"imageName" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
        waekSelf.imageView.image = [UIImage imageNamed:change[NSKeyValueChangeNewKey]];
    }];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([self.delegate respondsToSelector:@selector(viewDidClicked:)]) {
        [self.delegate viewDidClicked:self];
    }
}

@end


//
//  MVVM_Model.h
//  MVC_MVP_MVVM
//
//  Created by Rephontil.Zhou. on 2018/12/1.
//  Copyright © 2018 Rephontil.Zhou. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface MVVM_Model : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *imageName;
@end


Demo中,我引入了FB的轻量级KVO框架FBKVOController,在View中监听ViewModel属性的变化,以便及时更新View。

写了这么多,可能还不是很好理解。Demo运行一遍应该就一目了然了😊。

看到这里,点个赞呗❤️.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 155,958评论 4 358
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,179评论 1 286
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 105,792评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,409评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,723评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,174评论 1 204
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,543评论 2 306
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,270评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,899评论 1 236
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,235评论 2 240
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,771评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,139评论 2 249
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,688评论 3 228
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,936评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,646评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,194评论 2 265
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,145评论 2 258

推荐阅读更多精彩内容