MVVM

来源:互联网 发布:数据分析师累吗 编辑:程序博客网 时间:2024/05/01 23:20

MVVM 可以兼容你当下使用的 MVC 架构。
MVVM 增加你的应用的可测试性。
MVVM 配合一个绑定机制效果最好。
如我们之前所见,MVVM 基本上就是 MVC 的改进版,所以很容易就能看到它如何被整合到现有使用典型 MVC 架构的应用中。让我们看一个简单的 Person Model 以及相应的 View Controller:

  1. @interface Person : NSObject 
  2.  
  3. - (instancetype)initwithSalutation:(NSString *)salutation firstName:(NSString *)firstName lastName:(NSString *)lastName birthdate:(NSDate *)birthdate; 
  4.  
  5. @property (nonatomic, readonly) NSString *salutation; 
  6. @property (nonatomic, readonly) NSString *firstName; 
  7. @property (nonatomic, readonly) NSString *lastName; 
  8. @property (nonatomic, readonly) NSDate *birthdate; 
  9.  
  10. @end 

Cool!现在我们假设我们有一个 PersonViewController ,在 viewDidLoad 里,只需要基于它的 model 属性设置一些 Label 即可。

  1. - (void)viewDidLoad { 
  2.     [super viewDidLoad]; 
  3.  
  4.     if (self.model.salutation.length > 0) { 
  5.         self.nameLabel.text = [NSString stringWithFormat:@"%@ %@ %@", self.model.salutation, self.model.firstName, self.model.lastName]; 
  6.     } else { 
  7.         self.nameLabel.text = [NSString stringWithFormat:@"%@ %@", self.model.firstName, self.model.lastName]; 
  8.     } 
  9.  
  10.     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
  11.     [dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"]; 
  12.     self.birthdateLabel.text = [dateFormatter stringFromDate:model.birthdate]; 

这全都直截了当,标准的 MVC。现在来看看我们如何用一个 View Model 来增强它。

  1. @interface PersonViewModel : NSObject 
  2.  
  3. - (instancetype)initWithPerson:(Person *)person; 
  4.  
  5. @property (nonatomic, readonly) Person *person; 
  6.  
  7. @property (nonatomic, readonly) NSString *nameText; 
  8. @property (nonatomic, readonly) NSString *birthdateText; 
  9.  
  10. @end 

我们的 View Model 的实现大概如下:

  1. @implementation PersonViewModel 
  2.  
  3. - (instancetype)initWithPerson:(Person *)person { 
  4.     self = [super init]; 
  5.     if (!self) return nil; 
  6.  
  7.     _person = person; 
  8.     if (person.salutation.length > 0) { 
  9.         _nameText = [NSString stringWithFormat:@"%@ %@ %@", self.person.salutation, self.person.firstName, self.person.lastName]; 
  10.     } else { 
  11.         _nameText = [NSString stringWithFormat:@"%@ %@", self.person.firstName, self.person.lastName]; 
  12.     } 
  13.  
  14.     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
  15.     [dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"]; 
  16.     _birthdateText = [dateFormatter stringFromDate:person.birthdate]; 
  17.  
  18.     return self; 
  19.  
  20. @end 

Cool!我们已经将 viewDidLoad 中的表示逻辑放入我们的 View Model 里了。此时,我们新的 viewDidLoad 就会非常轻量:

- (void)viewDidLoad {
[super viewDidLoad];

self.nameLabel.text = self.viewModel.nameText;
self.birthdateLabel.text = self.viewModel.birthdateText;
}

所以,如你所见,并没有对我们的 MVC 架构做太多改变。还是同样的代码,只不过移动了位置。它与 MVC 兼容,带来更轻量的 View Controllers。

1 0