当Model与ViewModel完全相同时该怎么办? [英] What to do when Model is exactly the same as ViewModel?

查看:242
本文介绍了当Model与ViewModel完全相同时该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是最佳实践。我被告知要始终创建ViewModel,从不使用核心Model类将数据传递给Views。
这是有道理的。
让我把东西分开。但是什么是Model与ViewModel完全相同。我应该重新创建另一个课程,或者只是使用它。



我觉得我应该重新创建。只需要知道专家的意见。

解决方案

你应该还是创建一个单独的视图模型,即使它是相同的到您的域实体。视图模型和领域实体应该是完全独立的,即你应该能够改变一个,而不需要另外需要知道或关心变化。您的视图模型应该代表您的观点,您的域实体应该... ...代表您的域实体。现在他们可能是一样的,但是如果有任何一个变化,一个变化不应该影响另一个。



如果你的领域模型突然变化,现在有没有字段更长时间与您的观察模型相关?如果它们不是分开的,你有问题。或者,更糟(可能更可能),如果您的视图模式突然需要更多的信息,从一个完全不同的实体呢?您是否打破了您的领域模型中的类封装,这是完全不相关的信息,只是为了使您可以在您的视图中访问?



让您的解决方案脱钩和灵活。使用视图模型。


I want to know what is best practice. I have been told to always create ViewModels and never use core Model classes for passing data to Views. That makes sense. Lets me separate the things out. But what is Model is exactly the same as ViewModel. Should I recreate another class or just use it.

I feel that I should recreate. Just want to know what the experts say..

解决方案

You should definitely still create a separate view model, even if it is identical to your domain entity. The view model and the domain entity should be completely independent, i.e. you should be able to change one without the other needing to know or care about the change. Your view model should represent your view and your domain entity should... well... represent your domain entity. They might be identical now but, if either changes, the change in one should not affect the other.

What if your domain model suddenly changes and now has fields that are no longer relevant to your view model? If they aren't separate, you have a problem. Or, worse (and probably more likely), what if your view model suddenly needs more information, from a totally distinct entity? Are you going to break the encapsulation of classes in your domain model with this totally irrelevant information, just to make it accessible in your view?

Keep your solution decoupled and flexible. Use view models.

这篇关于当Model与ViewModel完全相同时该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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