I've had several questions about when and why to use M-V-VM versus other approaches.
The obvious purpose is abstraction of the View, reducing the amount of business logic or glue code stuck in code-behind.
All tasty goodness abstractly, but here's another concrete advantage: the ViewModel is easier to unit test than code-behind or event driven code.
The ViewModel, though it sounds View-ish is really more Model-ish, and that means you can test it without awkward UI automation and interaction.
If you've ever tried to unit test UI code, you know how hard that can be.
关于和其实设计模式相比,什么时候使用和为什么使用M-V-VM,我有几个疑问.
明显的目的是视图(View)的抽象,减少业务逻辑的数量或因视图分离时造成交互耦合.理论上看起来很美好,其实还有一个更实际的好处:视图-模型(ViewModel) 和视图分离或者事件驱动代码相比,更容易进行单元测试.
ViewModel尽管听起来是更具有视图特征,但是实际上它是更具有模型特征的.这意味着你可以不用笨拙的自动化UI或者交互就能测试它.如果你曾经试过对UI代码进行单元测试,你就知道那有多困难.
Disadvantages? For simple UI, M-V-VM can be overkill. In bigger cases, it can be hard to design the ViewModel up front in order to get the right amount of generality. Data-binding for all its wonders is declarative and harder to debug than nice imperative stuff where you just set breakpoints (though if you have lots of events running around, it may not be much different).
缺点?对于简单的UI,M-V-VM就有点过激了.更多时候,很难预先设计ViewModel来取得适量的普片性. 数据绑定好处是明确的,然而它却比好的硬性规则东西(例如你设的断点)更难调试.(如果你有很多事件正在执行,这可能不会有很大差异).
Data-binding performance is quite good, but it does tend to create a lot of general book-keeping data around. For awhile, we were adding a MultiBinding to every object we created. Loading a large file this meant 50,000 of them. In the WPF build we were using they were nearly 2K per...meaning the Bindings were heavier than the objects being bound. In this particular case I replaced the all the Bindings with a single static callback and saved nearly 100MB...! Normal UI won't create nearly so many bindings, but the perf is something to keep an eye on.
数据绑定的性能很好,但它趋于制造了很多通用记录数据.有时候,我们会添加一个多绑定的数据到每个我们创造的对象.加载很大的文件,这意味着5,000个它们.在WPF设计我们使用它们接近2K每个...意味着绑定的大小比对象本身还笨重.在这种特定的情况,我用单一静态的回调(callback)来代替所有绑定,节约了接近100MB...! 正常的UI不会制造那么多绑定.但是性能一直是我们需要注意的地方