13

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?

4

5 に答える 5

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);
于 2012-10-25T14:21:05.733 に答える
4

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

于 2012-10-25T14:21:28.633 に答える
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?

于 2016-03-20T02:14:35.257 に答える
1

オブジェクトのコンテキストを判断するのは少し難しいですが、技術的にはデザインパターンではありませんが、アセンブラパターンを見てください。アセンブラクラスは、あるオブジェクトから別のオブジェクトにマップするために使用されます。特に、あるオブジェクトがDTO(応答オブジェクトのようなもの)である場合は、ドメインオブジェクトにマップします。Dozerフレームワークは、これらの面倒な変換のいくつかを支援します。

于 2012-10-25T14:23:26.043 に答える
1

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

于 2012-10-25T14:12:03.453 に答える