介绍
这篇文章主要介绍了Java中转换器设计模式的作用是什么,小编觉得不错,现在分享给大家,也给大家做个参考,一起跟随小编来看看吧!
Java可以用来干什么
Java主要应用于:1。网页开发;2。Android开发;3。客户端开发;4。网页开发;5。企业级应用开发;6。Java大数据开发;7。游戏开发等。
<强>目的强>
转换器设计模式的目的是为相应类型之间的双向转换提供一种通用的方式,允许类型无需彼此了解的简洁的实现。此外,转换器设计模式引入了双向收集映射,将样板代码减少到最小。
<强>源代码强>
转换器设计模式是一种行为设计模式,允许在相应类型(如DTO和逻辑同构类型的域表示)之间进行双向转换。此外,该模式还引入了一种在类型之间转换对象集合的通用方法。
<强>类图强>
让我们根据上面的类图编写源代码。
在本例中,我们将把customerd转换为客户实体,反之亦然,我们还将在类型之间转换对象集合。
步骤1:让我们创建一个通用转换器。
public abstract class Converter & lt;, T, C 祝辞,{ ,private final  Function & lt;, T, ,C 祝辞fromDto; ,private final  Function & lt;, C, ,T 祝辞fromEntity;/* * *,才能@param fromDto *才能,,,Function that converts given dto entity into 从而域 ,,*,实体。 *,才能@param fromEntity *才能,,,Function that converts given domain entity into 从而dto ,,*,实体。 ,*/,public 转换器(final Function & lt;, T, C 祝辞,fromDto,, final Function & lt;, C, T 祝辞,fromEntity), { 时间=this.fromDto 才能;fromDto; 时间=this.fromEntity 才能;fromEntity; ,}/* * *,才能@param customerDto ,,*,DTO 实体 *,才能@return 从而domain representation 作用;从而result of 从而converting 函数 *才能,,,application 提醒dto 实体。 ,*/,public final  C convertFromDto (final T  customerDto), { return 才能fromDto.apply (customerDto); ,}/* * *,才能@param 客户 ,,*,domain 实体 *,才能@return 从而DTO representation 作用;从而result of 从而converting 函数 *才能,,,application 提醒domain 实体。 ,*/,public final  T convertFromEntity (final C 顾客),{ return 才能fromEntity.apply(客户); ,}/* * *,才能@param dtoCustomers ,,*,collection of DTO 实体 *,才能@return List of domain representation of provided entities retrieved 通过 *才能,,,mapping each of them with 从而conversion 函数 ,*/,public final  List & lt;, C 祝辞,createFromDtos (final Collection & lt;, T 祝辞,dtoCustomers), { return 才能;dtoCustomers.stream () . map (:: convertFromDto) .collect (Collectors.toList ()); ,}/* * *,才能@param 客户 ,,*,collection of domain 实体 *,才能@return List of domain representation of provided entities retrieved 通过 *才能,,,mapping each of them with 从而conversion 函数 ,*/,public final  List & lt;, T 祝辞,createFromEntities (final Collection & lt;, C 祝辞,客户),{ return 才能;customers.stream () . map (:: convertFromEntity) .collect (Collectors.toList ()); ,} }
步骤2:让我们创建一个简单客户转换器的实现。
public class CustomerConverter extends Converter, { ,public CustomerConverter (), { ,超级(customerDto →, new 客户(customerDto.getCustomerId (),, customerDto.getCustomerName (), ,customerDto.getCustomerLastName (),, customerDto.isStatus ()), ,customer →new CustomerDto (customer.getCustomerId (),, customer.getCustomerName (), customer.getCustomerLastName才能(),,customer.isStatus ())); ,} } Java中转换器设计模式的作用是什么