DTO的父/子模型 [英] Parent/child model for DTO

查看:122
本文介绍了DTO的父/子模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这种情况是否与泛型而不是 DTO 有关,但是在这里:

I am not sure if this situation would more be related to generics than DTOs, but here it goes:

我有一个代表人员的DTO. 人员可以和其他人员一样,也可以只有 ResourceLink 与这些人员强>.这意味着孩子可以是以下两种类型之一: Person (DTO)或 ResourceLink .它将是哪种类型,是通过 queryParam 确定的,因此在逻辑上通过以下流程确定.我只想使用 ONE 集合对象来表示它们,却不知道这样做的最佳方法.

I have a DTO that represents a Person. A Person can have as children other Person(s) or just ResourceLink to those Person(s). This means that the child can be of either of the 2 types: Person (the DTO) or the ResourceLink. What type it would be, is determined through a queryParam and consequently logically through the flow follwed. I want to represent them using just ONE collection object and am not aware of the best way to do so.

这是我到目前为止所拥有的:

Here is what I have so far:

public class PersonDTO<T> {

    @XmlElementWrapper(name = "children")
    @XmlElement(name = "child")
    List<T> children;
    // other stuff

}

使用这种方法,我需要根据if...else条件定义翻译类型.

With this approach, I need to define the translated type based on an if...else condition.

之前我有2个不同的集合,其中一个保持为 NULL .我还考虑过在新的DTO中将 relationship 内容提取为ChildrenDTO(不确定这是否是个好主意)

Earlier I had 2 different collections, one of which remained NULL. I also thought of extracting the relationship thing out in a new DTO as ChildrenDTO (not sure if that's a great idea)

我想知道这种情况是否有最佳实践,否则,是否有可能根据条件声明PersonDTO<PersonDTO>PersonDTO<ResourceLink>.

I would like to know if there is a best practice for this situation, otherwise, if it is possible to declare a PersonDTO<PersonDTO> or PersonDTO<ResourceLink> depending on a condition.

提前谢谢!

推荐答案

我建议使用List子元素的第三种类型:

I'd suggest instead, using a third type for the elements of List children:

    public interface PersonResolver () {
          Person resolvePerson ();
    }

    public class Person implements PersonResolver {
          Person resolvePerson () { return this; }
    }

    public class ResourceLink implements PersonResolver {
          Person resolvePerson () {
               if (myLinkTargetType == TARGET_TYPE_PERSON)
                      { return (Person) myTarget; }
               return null;
          }
    }

这篇关于DTO的父/子模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆