Object-Oriented Design – Different Ways to Serialize an Object

design-patternsobject-orientedserialization

It is usual for me, when doing web development, to copy attributes from my model classes to the other class that will be sent to the client. Usually, with a class that accepts a model and extracts the necessary information this is sufficient (something like a adapter I suppose), but sometimes it is not that easy.

In some systems, for different reasons I need to send a different sets of attributes, and this is where simplicity seems to disappears.

With my usual approach I end up with lot's of classes very similar one from each other, just because one is for being used in one channel that requires some information and the others for channels that require very similar information. But cannot be the same sum of the two because performance or security. (When I say channels it is because it could be a serialized using json or xml, or used in other protocols, or just displayed as html by the server.)

The question is: Is there a pattern that allows for different transformations of a object (that might aggregate others objects) depending the context being used? (without too much code duplication)

Case of study: in a distributed cards game (like poker), I need to send to every user the score, the name of the players, the cards that were played, and the cards he has in his hand. But when the game ends I need to send the cards in the hands of the others players too. And in other view of the game I need to send only the score and the name of the players.

Sorry about my English, it is not my first language (and the idea I am trying to communicate seems a little complex for me).

Best Answer

What you are doing right now is the Data Transfer Pattern.

You might want take a look at 'composition' (Robert Martin). It's not really a pattern but rather a guideline.

Related Topic