什么是数据传输对象?

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


当前回答

DTO的定义可以在Martin Fowler的网站上找到。dto用于将参数传递给方法并作为返回类型。很多人在UI中使用它们,但其他人从它们扩展域对象。

其他回答

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.

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

从维基百科:

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

DTO的定义可以在Martin Fowler的网站上找到。dto用于将参数传递给方法并作为返回类型。很多人在UI中使用它们,但其他人从它们扩展域对象。

我会把DTO解释给我的孩子

我的儿子,数据传输对象(又名DTO) **用于封装我们从一个端点发送到另一个端点的数据。 使用DTO为系统中的端点定义输入和输出接口 在这种情况下,可以将系统看作端点的集合。端点可以是任何相互通信的东西(移动应用程序,web应用程序,后端API)。

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