欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 【设计模式】JAVA Design Patterns——Data Transfer Object(数据传递对象模式)

【设计模式】JAVA Design Patterns——Data Transfer Object(数据传递对象模式)

2024/10/24 15:14:07 来源:https://blog.csdn.net/CSBIGDOG/article/details/139253597  浏览:    关键词:【设计模式】JAVA Design Patterns——Data Transfer Object(数据传递对象模式)

🔍目的


次将具有多个属性的数据从客户端传递到服务器,以避免多次调用远程服务器

🔍解释


真实世界例子

我们需要从远程数据库中获取有关客户的信息。 我们不使用一次查询一个属性,而是使用DTO一次传送所有相关属性。

通俗描述

使用DTO,可以通过单个后端查询获取相关信息。

维基百科

在编程领域,数据传输对象(DTO)是在进程之间承载数据的对象。 使用它的动机是,通常依靠远程接口(例如Web服务)来完成进程之间的通信,在这种情况下,每个调用都是昂贵的操作。

因为每个(方法)调用的大部分成本与客户端和服务器之间的往返时间有关,所以减少调用数量的一种方法是使用一个对象(DTO)来聚合将要在多次调用间传输的数据,但仅由一个调用提供。

程序示例

创建一个简单的CustomerDTO 类

public class CustomerDto {private final String id;private final String firstName;private final String lastName;public CustomerDto(String id, String firstName, String lastName) {this.id = id;this.firstName = firstName;this.lastName = lastName;}public String getId() {return id;}public String getFirstName() {return firstName;}public String getLastName() {return lastName;}
}

创建CustomerResource 类充当客户信息的服务器。

public class CustomerResource {private final List<CustomerDto> customers;public CustomerResource(List<CustomerDto> customers) {this.customers = customers;}public List<CustomerDto> getAllCustomers() {return customers;}public void save(CustomerDto customer) {customers.add(customer);}public void delete(String customerId) {customers.removeIf(customer -> customer.getId().equals(customerId));}
}

从而拉取客户信息就简单了

 

    var allCustomers = customerResource.getAllCustomers();allCustomers.forEach(customer -> LOGGER.info(customer.getFirstName()));// Kelly// Alfonso

🔍类图

🔍适用场景

使用数据传输对象模式当

  • 客户端请求多种信息。信息都是相关的
  • 当你想提高获取资源的性能
  • 你想降低远程方法调用的次数

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com