MVVM 简单理解

MVVM

MVC 虽然一直是苹果建议的一种设计模式,但是 View 与 Controller 的耦合度过高,而 Controller 往往会变得越来越臃肿,因此常被戏称为 Massive View Controller(重量级视图控制器)。
于是 MVVM (Model-View-ViewModel)应运而生 。
既然View 与 Controller 的耦合度总是过高,那么不如就将它们正式连接起来,并将表示逻辑(presentation logic)抽离出来形成 ViewModel。其本质上是优化后的 MVC 架构。


so , talk is cheap show me the code

这是一个简单的 PersonModel

@interface PersonModel : NSObject

- (instancetype)initwithSalutation:(NSString *)salutation
                         firstName:(NSString *)firstName
                          lastName:(NSString *)lastName
                         birthdate:(NSDate *)birthdate;

@property (nonatomic, readonly) NSString *salutation;
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSDate   *birthdate;

@end

对应的 PersonalViewModel

@interface PersonalViewModel : NSObject

- (instancetype)initWithPerson:(PersonModel *)person;

@property (nonatomic, readonly) PersonModel *person;
@property (nonatomic, readonly) NSString    *nameText;
@property (nonatomic, readonly) NSString    *birthdateText;

@end

内部实现,将原本在 controller 中的工作抽离出来

@implementation PersonalViewModel

- (instancetype)initWithPerson:(PersonModel *)person {
    self = [super init];
    if (!self) return nil;
    
    _person = person;
    if (person.salutation.length > 0) {
        _nameText = [NSString stringWithFormat:@"%@ %@ %@",
                     self.person.salutation,
                     self.person.firstName,
                     self.person.lastName];
    } else {
        _nameText = [NSString stringWithFormat:@"%@ %@",
                     self.person.firstName,
                     self.person.lastName];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
    _birthdateText = [dateFormatter stringFromDate:person.birthdate];
    
    return self;
}

现在 controller 中就变得十分精简了

    // 变得非常轻量的赋值
    self.nameLable.text = self.viewModel.nameText;
    self.birthdateLabel.text = self.viewModel.birthdateText;

demo 地址

MVVM 总结

通过学习感觉 MVVM 并不是一种新奇的设计模式,它更像是 MVC 的一种完善,核心思想在于抽离复杂的业务逻辑产生 viewModel 层,降低耦合度。而使 MVVM 实现响应式编程,变得更加好用,可以引入 ReactiveCocoa 的 配合。

参考资料:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容