Design pattern for converting one model to another model
Solution 1
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
Solution 2
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);
Solution 3
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?
Solution 4
You probably look for the adapter pattern: http://en.wikipedia.org/wiki/Adapter_pattern
Solution 5
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.
Related videos on Youtube
Ashay Batwal
Updated on September 14, 2022Comments
-
Ashay Batwal over 1 year
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?
-
Jigar Parekh over 11 years
-
-
Ashay Batwal over 11 yearsYes I can, but in my case I only have two simple POJO's and no interfaces. Isn't there any other pattern or better way of doing the transformation.
-
SomeWittyUsername over 11 yearsYou can take a look at proxy pattern but really it depends on your preferences and environment.
-
Matthijs Wessels over 11 yearsWhy would the Facade pattern solve his problem? Isn't that pattern used to "provide a simplified interface to a larger body of code"? I don't think you are supposed to put the conversion logic in the facade.
-
johnlemon over 10 yearsAdapter 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.