MVVM模式的简单通俗理解

VanBurford 7年前
   <p>目前MVVM模式是移动开发里面讨论的较多的开发设计模式了,随之而来的还有ReactiveCocoa框架。但是MVVM设计模式并不意味着非要用ReactiveCocoa框架,毕竟这个框架是一个重型框架,一般的应用也不用搞得这么复杂。前些时公司app改版,使用MVVM模式重构了一下代码,这里写下来仅仅是记录我这一段时间的实践总结,希望能尽量说明白一点。</p>    <h3><strong>1、MVVM和MVC的区别</strong></h3>    <p>MVC不用说了,都清楚。MVVM的话,所有讲MVVM的文章都会拿出这个图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/bcb1e80f39cb292ad8f7454bd5f2b43b.png"></p>    <p>与MVC的区别在于中间多了个View Model,以前的MVC是view controller直接和model打交道,然后用model去填充view。这里MVVM的view model把view controller/view和model隔开了。理论就说道这里,那么问题是:</p>    <p>1、这样做的好处是什么?</p>    <p>2、怎么设计这个view model?</p>    <h3><strong>2、MVC我们是怎么写代码的?</strong></h3>    <p>比如这个普通的评论列表:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9ee5b38eaddb91700e87361d2d578a53.png"></p>    <p>这个评论列表有三个地方要注意:一是动态行高,二是点赞数根据数量大小有不同的显示,三是回复评论前面要加上颜色不同的“@XX”。一般MVC写代码是这样的,代码结构如下:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/7f2fe16b8dd432fc76f5d473cbb5814f.png"></p>    <p>下面是主要代码:</p>    <pre>  <code class="language-objectivec">@implementation KTCommentsViewController    - (void)viewDidLoad {      [super viewDidLoad];      // Do any additional setup after loading the view from its nib.        self.title = @"评论列表";      [self.tableView registerNib:[UINib nibWithNibName:@"KTCommentCell" bundle:nil] forCellReuseIdentifier:kKTCommentCellIdentifier];      [self createData];  }    // 1、获取数据  - (void)createData  {      NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];      for (NSUInteger ii = 0; ii < 20; ++ii) {          KTComment *comment = [[KTComment alloc] init];          comment.commentId = ii + 1;          [array addObject:comment];          comment.userName = [NSString stringWithFormat:@"名字%lu", (unsigned long)(ii + 1)];          comment.userAvatar = @"user_default";          NSMutableArray *strsArray = [NSMutableArray arrayWithCapacity:ii + 1];          for (NSUInteger jj = 0; jj < ii + 1; ++jj) {              [strsArray addObject:@"这是评论"];          }          comment.content = [strsArray componentsJoinedByString:@","];          comment.commentTime = [NSDate date];          if (ii % 3 == 0) {              comment.repliedUserId = 10;              comment.repliedUserName = @"张三";              comment.favourNumber = 1000 * 3 * 10 * ii;          } else {              comment.favourNumber = 3000 * ii;          }      }      self.commentsList = array;  }    #pragma mark -- tableView --    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  {      return self.commentsList.count;  }    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  {      // 2、计算高度      KTComment *comment = [self.commentsList objectAtIndex:indexPath.row];      CGFloat width = [UIScreen mainScreen].bounds.size.width - 10 - 12 - 35 - 10;      CGFloat commnetHeight = [comment.content boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;        return commnetHeight + 15 + 21;  }    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {      KTCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kKTCommentCellIdentifier forIndexPath:indexPath];      KTComment *comment = [self.commentsList objectAtIndex:indexPath.row];      cell.comment = comment;        return cell;  }</code></pre>    <pre>  <code class="language-objectivec">// KTCommentCell  - (void)setComment:(KTComment *)comment  {      _comment = comment;        [_avatarImageView setImage:[UIImage imageNamed:comment.userAvatar]];      [_nameLabel setText:comment.userName];      [_timeLabel setText:[comment.commentTime ov_commonDescription]];      // 3、判断是否是回复评论的逻辑      if (comment.repliedUserName.length > 0) {          NSMutableAttributedString *attrContent = [[NSMutableAttributedString alloc] init];          NSString *header = [NSString stringWithFormat:@"@%@ ", comment.repliedUserName];          NSAttributedString *reply = [[NSAttributedString alloc] initWithString:header attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor blueColor]}];          [attrContent appendAttributedString:reply];          NSAttributedString *content = [[NSAttributedString alloc] initWithString:comment.content attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor darkGrayColor]}];          [attrContent appendAttributedString:content];          [_commentLabel setAttributedText:attrContent];      } else {          [_commentLabel setText:comment.content];      }      // 4、根据点赞数量显示“改造”后的点赞数量的逻辑      NSString *favourString = nil;      if (comment.favourNumber == 0) {          favourString = nil;      } else if (comment.favourNumber < 10000) {          favourString = [NSString stringWithFormat:@"%lld赞", comment.favourNumber];      } else if (comment.favourNumber < 10000) {          float floatNum = (double)comment.favourNumber / 10000.0;          favourString = [NSString stringWithFormat:@"%.1f万赞", floatNum];      } else {          NSInteger intNum = comment.favourNumber / 10000;          favourString = [NSString stringWithFormat:@"%ld万赞", (long)intNum];      }      _favourLabel.text = favourString;  }</code></pre>    <p>MVC模式里面,可以看出我们的view controller和view(KTCommentCell)是直接和Model(KTComment)打交道的,对于数据的处理逻辑,也是直接写在view controller和view中的,比如:</p>    <p>1、获取数据:如上面的标注1处,如果这个地方的逻辑变得复杂,比如有缓存数据,先要读取数据库,然后判断有没有缓存数据,没有的话请求网络,数据回来之后还要解析,那么1处的代码会变得冗长。</p>    <p>2、行高计算:很多应用都涉及到动态行高计算,像标注2处写在这里首先是让view controller臃肿,另外这个行高方法会频繁调用,那么频繁计算会严重影响tableView的滑动性能。</p>    <p>3、数据加工逻辑:有些model的属性是不能直接为view所用的,比如上面3、4两处需要将model的属性加工一下再显示,MVC中这个加工逻辑也是写在view中的。</p>    <p>这只是一个简单的例子,简单的例子这样些没有什么大问题。但是如果遇到比较复杂的界面,这么写下去会导致view controller和view的代码越来越多,而且难以复用,MVC就变成了胖view controller模式。</p>    <h3><strong>3、MVVM怎么写?</strong></h3>    <p>MVVM的提出就是为了减轻view controller和view的负担的,view model将上面提到的获取数据,行高计算,数据加工逻辑从view controller和view中剥离出来,同时把view controller/view和model隔开。</p>    <p><strong>3.1、剥离行高计算,数据加工逻辑</strong></p>    <p>如下所示,添加view model:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/3d9d82ca2760cff555ad704394653f9c.png"></p>    <p>下面是代码示例:</p>    <pre>  <code class="language-objectivec">@interface KTCommentViewModel : NSObject    @property (nonatomic, strong) KTComment *comment;  // 根据文本多少计算得到行高  @property (nonatomic, assign) CGFloat cellHeight;  // 根据是否是回复,计算得到的富文本  @property (nonatomic, copy) NSAttributedString *commentContent;  // 根据点赞数计算得到的显示文字  @property (nonatomic, copy) NSString *favourString;    @end    @implementation KTCommentViewModel    - (void)setComment:(KTComment *)comment  {      _comment = comment;        // 1、计算行高,并用属性存起来      // 2、根据是否是回复,计算得到的富文本      // 3、根据点赞数计算得到的显示文字  }    @end</code></pre>    <p>这里的1、2、3处的代码基本上等同于将前面view、view controller中2、3、4处的代码拷贝过来,这里就省略了。可以看出view model的作用是:</p>    <p>1、和model打交道。</p>    <p>2、做一些逻辑处理和计算。</p>    <p>3、和view、view controller打交道,并提供更为直观的数据,比如上面的行cellHeight,commentContent,favourString等属性。</p>    <p>这样一来,上面的2、3、4处的代码被移到view model中了,view、view controller清爽了很多,而且职责更加分明,行高频繁计算也避免了,因为行高被view model给缓存了,只计算一遍就行了。下面是view controller和view的变化:</p>    <pre>  <code class="language-objectivec">- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  {      KTCommentViewModel *viewModel = [self.commentsList objectAtIndex:indexPath.row];        return viewModel.cellHeight;  }    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {      KTCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kKTCommentCellIdentifier forIndexPath:indexPath];      KTCommentViewModel *viewModel = [self.commentsList objectAtIndex:indexPath.row];      cell.commentViewModel = viewModel;        return cell;  }    //  KTCommentCell  - (void)setCommentViewModel:(KTCommentViewModel *)commentViewModel  {      _commentViewModel = commentViewModel;        [_avatarImageView setImage:[UIImage imageNamed:commentViewModel.comment.userAvatar]];      [_nameLabel setText:commentViewModel.comment.userName];      [_timeLabel setText:[commentViewModel.comment.commentTime ov_commonDescription]];      _commentLabel.attributedText = commentViewModel.commentContent;      _favourLabel.text = commentViewModel.favourString;  }</code></pre>    <p><strong>3.2、剥离获取数据逻辑</strong></p>    <p>如下创建一个列表view model:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/1752c21334556b6ee30166a8931930c7.png"></p>    <p>代码示例如下:</p>    <pre>  <code class="language-objectivec">@interface KTCommentListViewModel : NSObject    @property (nonatomic, copy) NSArray<KTCommentViewModel *> *commentViewModelList;    - (void)loadComments;    @end</code></pre>    <p>KTCommentListViewModel的职责也很清楚,就是负责获取数据,然后为每个comment创建一个KTCommentViewModel对象,并保存到列表中。那么view controller就可以将获取数据的代码挪到这个view model中来,view controller只用调用KTCommentListViewModel提供的方法和数据就可以了:</p>    <pre>  <code class="language-objectivec">- (void)viewDidLoad {      [super viewDidLoad];      // Do any additional setup after loading the view from its nib.        self.commentListViewModel = [[KTCommentListViewModel alloc] init];      [self.commentListViewModel loadComments];  }</code></pre>    <h3><strong>4、总结</strong></h3>    <p>基本上算是搞懂了第一张图的含义。view和view controller拥有view model,view model拥有model,相比较MVC的区别在于view和view controller是通过view model来间接操作数据的。这样做的意义在于,对于一些比较复杂的操作逻辑,可以写到view model里面,从而简化view和view controller,view和view controller只干展示数据和接受交互事件就好了;翻过model的update,驱动view model的update,然后再驱动view和view controller变化,这个中间的加工逻辑也可以写在view model中。</p>    <p>当然对于一些比较简单的应用界面,使用MVC就绰绰有余了,并不需要用MVVM,用哪种还要看实际情况和个人喜好吧。</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/aed9a3705991</p>    <p> </p>