Parent/child model for DTO

只愿长相守 提交于 2019-12-11 17:17:25

问题


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

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

}

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

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)

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.

Thanks in advance!


回答1:


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;
          }
    }


来源:https://stackoverflow.com/questions/8544309/parent-child-model-for-dto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!