实现的基本Java Service类

问题描述 投票:1回答:2

有一个具有以下方法的基本服务接口:

public interface BaseService {

    Dto convertToDto(Entity entity);
    List<Dto> convertToDtoList(List<Entity> entityList);
    Entity convertToEntity(Dto dto);
    List<Entity> convertToEntityList(List<Dto> dtoList);

}

现在方法convertToDtoListconvertToEntityList应该在基本服务实现中实现,然后由其他服务扩展,以便这些方法只需要在基本服务中实现一次。 convertToDtoListconvertToEntityList始终具有相同的实现,只是它们使用各自服务类的不同实体和dto类型:

public List<Dto> convertToDtoList(List<Entity> entityList) {
    if (entityList == null)
        return null;

    List<Dto> dtoList = new ArrayList<Dto>();
    Iterator<Entity> it = entityList.iterator();

    while (it.hasNext())
        dtoList.add(this.convertToDto(it.next()));

    return dtoList;
}


public List<Entity> convertToEntityList(List<Dto> dtoList) {
    if (dtoList == null)
        return null;

    List<Entity> entityList = new ArrayList<Entity>();
    Iterator<Dto> it = dtoList.iterator();

    while (it.hasNext())
        entityList.add(this.convertToEntity(it.next()));

    return entityList;
}

如何在基本服务中以从各个实体和dto类型抽象的通用方式实现这些方法,以便可以在扩展该基本服务的每个服务类中使用它们?

java
2个回答
1
投票

您可以在界面和模板<>中使用默认实现:

public interface BaseService<D, E> {

    D convertToDto(E entity);

    E convertToEntity(D dto);

    default List<E> convertToEntityList(List<D> dtoList) {
        return Optional.ofNullable(dtoList).orElse(Collections.emptyList()).stream()
                       .map(this::convertToEntity)
                       .filter(Objects::nonNull)
                       .collect(Collectors.toList());
    }

    default List<D> convertToDtoList(List<E> entityList) {
        return Optional.ofNullable(entityList).orElse(Collections.emptyList()).stream()
                       .map(this::convertToDto)
                       .filter(Objects::nonNull)
                       .collect(Collectors.toList());
    }

}

public class DtoEntityBaseService implements BaseService<Dto, Entity> {

    @Override
    public Dto convertToDto(Entity entity) {}

    @Override
    public Entity convertToEntity(Dto dto) {}
}

您可以看到非常有用的框架,这些框架可以帮助完成所有这些任务转型。它调用Mapsruct


1
投票

执行以下操作:

public interface BaseService <T> {

    Dto convertToDto(Entity entity);
    default public List<Dto> convertToDtoList(List<T> entityList) {
        if (entityList == null)
            return null;

        List<Dto> dtoList = new ArrayList<Dto>();
        Iterator<T> it = entityList.iterator();

        while (it.hasNext())
            dtoList.add(this.convertToDto(it.next()));

        return dtoList;
    }

    default public List<Entity> convertToEntityList(List<T> dtoList) {
        if (dtoList == null)
            return null;

        List<Entity> entityList = new ArrayList<Entity>();
        Iterator<T> it = dtoList.iterator();

        while (it.hasNext())
            entityList.add(this.convertToEntity(it.next()));

        return entityList;
    }
    Entity convertToEntity(Dto dto);
}

检查this了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.