问题
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