实现的基本Java服务类
存在具有以下方法的基本服务接口:
public interface BaseService {
Dto convertToDto(Entity entity);
List<Dto> convertToDtoList(List<Entity> entityList);
Entity convertToEntity(Dto dto);
List<Entity> convertToEntityList(List<Dto> dtoList);
}
现在,方法ConvertToToList和convertToEntityList应该在基本服务实现中实现,然后由其他服务扩展,这样这些方法只需在基本服务中实现一次。ConvertToList和convertToEntityList始终具有相同的实现,只是它们使用不同的实体和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类型抽象出来的通用方式实现这些方法,以便在扩展此基本服务的每个服务类中使用它们
# 1 楼答案
按如下方式操作:
查看this了解更多信息
# 2 楼答案
您可以在接口和模板
<>
中使用默认实现: