14

Basically, I have a number of objects in my application and I have to convert them to another third party objects before sending the request. On receiving the response I have to convert these objects back to objects supported by my application.

What pattern can I use for converting one model object to another in Java?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Ashay Batwal
  • 5,415
  • 7
  • 25
  • 30

5 Answers5

9

I don't think there is a specific pattern for this, but you simply need a "converter" or "translator" class that takes in one object and returns another:

MyObject convert(ThirdPartyObject obj);
ThirdPartyObject convert(MyObject obj);
casablanca
  • 69,683
  • 7
  • 133
  • 150
5

Either Adapter or facade pattern should solve your problem:

Adapter: http://www.youtube.com/watch?v=TriX8OiEhOU

Facade: http://www.youtube.com/watch?v=WLjvNpP6yeQ

  • 10
    Why would the Facade pattern solve his problem? Isn't that pattern used to ["provide a simplified interface to a larger body of code"](http://en.wikipedia.org/wiki/Facade_pattern)? I don't think you are supposed to put the conversion logic in the facade. – Matthijs Wessels Oct 27 '12 at 22:23
  • 1
    Adapter is also an overkill and should be used only if you need data changed in the base model to reflect in the new model. A converter class would also help separating responsibilities. – johnlemon Sep 09 '13 at 09:08
4

Adapter and Facade are structural patterns. You don't have any patterns to cater to Object transformation.

On creational pattern front, Builder is one pattern you can think of.

Generally Builder pattern is used to build object with mandatory and optional parameter. But you can fine tune it by building necessary object.

You can solve the problem without pattern too. Either you can use Object composition or Write your own method to transform the object.

Have a look at related SE question with code example:

How to prune an object of some of its fields in Java?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
1

You probably look for the adapter pattern: http://en.wikipedia.org/wiki/Adapter_pattern

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
1

It's a bit hard to determine the context of the objects, but take a look at the Assembler pattern, although not technically a design pattern. An Assembler class is used to map from one object to another, specifically when one object is a DTO (kind of like your response object) to a Domain object. The Dozer framework can help you with some of these tedious transformations.

tjg184
  • 4,508
  • 1
  • 27
  • 54