什么是数据传输对象?

在MVC模型类DTO,如果不是什么区别,我们需要两者吗?


当前回答

DTO是一个愚蠢的对象——它只保存属性,有getter和setter,但没有任何其他重要的逻辑(除了一个compare()或equals()实现)。

通常MVC中的模型类(假设这里是。net MVC)是dto,或者dto的集合/聚合

其他回答

一些程序员使用DTO来区分将通过API传递的最终对象数据。它基本上是端点的有效载荷对象。比如,你可以将你传递给服务器的联系人表单值对象命名为contactFormDto或contactFromPayload,然后你或任何其他程序员都知道你在那个对象中拥有的是数据的最终形状,它将通过网络传播。

在MVC中,数据传输对象通常用于将域模型映射到最终由视图显示的更简单的对象。

从维基百科:

数据传输对象(DTO),以前称为值对象或VO 一种用于在软件应用程序之间传输数据的设计模式 子系统。dto通常与数据访问一起使用 对象从数据库检索数据。

DTO是一个愚蠢的对象——它只保存属性,有getter和setter,但没有任何其他重要的逻辑(除了一个compare()或equals()实现)。

通常MVC中的模型类(假设这里是。net MVC)是dto,或者dto的集合/聚合

数据传输对象(DTO)描述了“承载数据的对象” (维基百科)或“用于封装数据的对象”, 并将它从应用程序的一个子系统发送到另一个子系统”(堆栈溢出 答案)。

To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.