且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

值对象模式和数据传输模式之间的区别

更新时间:2023-02-07 13:49:28

DTO是可以在系统的边界上使用的对象.例如,当您具有SOAP Web服务并且想要返回响应时,可以使用DTO.与必须通过网络返回的实际XML相比,处理起来要容易得多. DTO通常由工具生成,例如基于WSDL. DTO通常是根据服务使用者的需求量身定制的,并且会受到性能要求的影响.

DTO is the object that you can use at the boundaries of the system. When you have a SOAP web service for example and you want to return response you would use DTO. It easier to deal with than actual XML that has to be returned over the wire. DTOs are often generated by tools, based on WSDL for example. DTO are often tailored to the needs of service consumer and can be affected by performance requirements.

值对象位于系统的核心中.它捕获了业务逻辑,甚至还有格式规则.它使您的代码更安全和更具表现力.它还解决了原始痴迷"的反模式.一个很好的例子是使用类"SocialSecurityNumber"代替字符串.或用钱代替小数.这些对象应该是不可变的,以使它们看起来更像基元,并且可以轻松地在不同线程之间共享.

Value objects on the other hand live in the core of the system. It captures pieces of business logic and maybe formatting rules. It makes your code more type safe and expressive. It also tackles "Primitive obsession" anti pattern. Good example is using class "SocialSecurityNumber" instead of string. Or Money instead of decimal. These objects should be immutable so that they look more like primitives and can be easily shared among different threads.

例如在假设的客户订单"系统中:

For example in hypothetical 'customer-order' system:

CustomerAndLastFiveOrders 是DTO(已优化,可避免多次网络通话)

CustomerAndLastFiveOrders is DTO (optimized to avoid multiple network calls)

客户是实体

金钱 SKU 是价值对象