Java – Design pattern for object conversion (java)

design-patternsjavaobject

I don't use design patterns very often, besides an occasional factory and MVC, and I want to start using them more.

I have a concrete case at hand that I would like your opinion on the use of design patterns in this case.

In my application I have to convert objects pretty often in different situations. I might have to convert a Hibernate POJO to a DTO, because I use GWT and Hibernate POJO's aren't serializable and can't be sent over the line.

In another situation I might need to convert Java objects to SolrInputDocument's for indexing by Solr.

I would like to know if I should use a design pattern for this. It seems that "object conversion" is a generic task that could be handled in a flexible/abstract way by a pattern, but I don't really see how.

Without patterns I would just create a separate class for each type of conversion, for example CourseToSolrInputDocument (Course is a Hibernate entity in my application). Or CourseToCourseDTO. Each of these conversion classes might have a single static method called convert() that takes the source object as input and returns the output object.

But that is not really a pattern, is it? So I started of on something with generics and created this class that implements the Converter interface. But is somehow feels silly tgo create a generic interface and I don't really see the advantage other than being able to congratulate myself on the use of generics.

public class CourseToSolrInputDocument implements Converter<Course, SolrInputDocument>         {
    @Override
    public void convert(Course source, SolrInputDocument destination) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}

So, the real question here is: is there a pattern that applies to generic object conversion and, what would be your approach and what are the advantages over using just a class-per-conversion type approach?

Best Answer

The Translator Pattern is what you're asking for.

But I suspect what you're looking for is a framework, more than a pattern. I believe Dozer is popular in the Java world.