I have many DTO objects. Every dto class have the methods
convertDTO(Entity entity)convertDTOList(List<Entity> entity) I want to use a desing pattern for my dto object converter. Which desing pattern I can use and how?
Dozer framework is good. But I want to write a generic pattern.
If you use Java8, I'd suggest to use DTO to domain converter pattern as suggested here
Below an implementation example:
GenericConverter
public interface GenericConverter<I, O> extends Function<I, O> {
    default O convert(final I input) {
        O output = null;
        if (input != null) {
            output = this.apply(input);
        }
        return output;
    }
    default List<O> convert(final List<I> input) {
        List<O> output = new ArrayList<O>();
        if (input != null) {
            output = input.stream().map(this::apply).collect(toList());
        }
        return output;
    }
}
ConverterDTO
public class AccountCreateRequestConverter implements GenericConverter<AccountCreateRequest, AccountOutput> {
    @Override
    public AccountOutput apply(AccountCreateRequest input) {
        AccountOutput output = new AccountOutput();
        output.setEmail(input.getEmail());
        output.setName(input.getName());
        output.setLastName(input.getLastName());        
        output.setPassword(input.getPassword());                                
        return output;
    }
}
Consumer
The consumer class:
class Consumer {
    @Inject
    AccountCreateRequestConverter accountCreateInputConverter;
    void doSomething() {
        service.registerAccount(accountCreateInputConverter.apply(input));
    }
}
The strength of this pattern come from the easiness to use, because you could pass either a single or a list of entities, in which there can be other nested DTO to convert using their dedicated converters inside the converter parent class. Something like this:
nested collection DTO converter example
class ParentDTOConverter {
    @Inject
    ChildDTOConverter childDTOConverter;
    void doSomething() {
        @Override
        public ParentDTOOutput apply(ParentDTOInput input) {
            ParentDTOOutput output = new ParentDTOOutput();
            output.setChildList(childDTOConverter.convert(input.getChildList()));
        }
    }
}
There are many different solutions. You can find a discussion about it here Object Conversion Pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With