如何在MVVM中构建ViewModel而不违反单一职责原则? [英] How to build the ViewModel in MVVM not to violate the Single Responsibility Principle?

查看:228
本文介绍了如何在MVVM中构建ViewModel而不违反单一职责原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

罗伯特·马丁说:改变班级的理由不应该超过一个".

让我们考虑绑定到View的ViewModel类. ViewModel可能(甚至可能)由彼此之间并不真正相关的属性组成.对于小视图,ViewModel可能非常连贯,但是当应用程序变得更加复杂时,ViewModel将公开由于不同和不相关的原因而可能更改的数据.

对于ViewModel类,我们是否应该担心SRP原则?

Robert Martin says: "There should never be more than one reason for a class to change".

Let's consider the ViewModel class which is bound to a View. It is possible (or even probable) that the ViewModel consists of properties that are not really related to each other. For small views the ViewModel may be quite coherent, but while the application gets more complex the ViewModel will expose data that will be subject to change for different and unrelated reasons.

Should we worry about the SRP principle in the case of ViewModel class or not?

推荐答案

ViewModel的唯一职责是向View提供所需的信息.如果View需要不同且不相关的属性,那么这并不重要,因为ViewModel仅具有更改的一个原因,那就是View显示了不同的属性.因此,您不必担心太多.

The ViewModel single responsibility is to provide the View the information it needs. If the View needs different and unrelated properties that is not important as the ViewModel only has one reason to change and that is the View showing different properties. So you shouldn't worry too much.

也就是说,如果ViewModel变得很大,也许您可​​以考虑将视图分为几个子视图以提高可重用性,并使View和ViewModels易于管理.

That said, if the ViewModel does get huge, maybe you could think about dividing the view into several subviews to improve reusability and keep the Views and the ViewModels manageable.

这篇关于如何在MVVM中构建ViewModel而不违反单一职责原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆