MVVM 简单理解

作者: 漂泊海上的大土豆 | 来源:发表于2017-03-31 10:37 被阅读94次

    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 的 配合。

    参考资料:

    相关文章

      网友评论

        本文标题:MVVM 简单理解

        本文链接:https://www.haomeiwen.com/subject/ykwmottx.html