Suppose I have following class hierarchy:
class abstract Parent{}
class FirstChild extends Parent {}
class SecondChild extends Parent {}
And I'd like to create DTO objects from each child:
class abstract ParentDTO {}
class FirstChildDTO extends ParentDTO{}
class SecondChildDTO extends ParentDTO{}
I think I need a factory method something like this:
ParentDTO createFrom(Parent source);
Is there any nice way to do this in Java without instanceof
checks and if/else statements?
EDIT: This factory method does not work:
public ParentDTO create(Parent source)
{
return _create(source);
}
private FirstChildDTO _create(FirstChild source)
{
return new FirstDTO();
}
private SecondChildDTO _create(SecondChild source)
{
return new SecondDTO();
}
private ParentDTO _create(Parent source)
{
return new ParentDTO();
}
It only generates ParentDTO
s and here is why:
Parent p = new FirstChild();
System.out.println(factory.create(p)); //ParentDTO
FirstChild f = new FirstChild();
System.out.println(factory.create(f)); //FirstChildDTO