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).

| improve this question | | | | |
  • Just use a different object type for the other view. The end of the game can be done by just having multiple objects. – Robert Harvey Jul 14 '13 at 1:42

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.

| improve this answer | | | | |
  • Just for being the first to respond and taught me the name of what I was doing, I am choosing this answer as correct. But @matcauthon is worthy. – Fernando Aug 19 '13 at 23:50

This might be solveable with the use of different design patterns. This will lead to a generic approach, but it might be not so effiecient and easy to understand.

For serializing you can use Memento. If you want to serialize depending on some state or so you can use State or Strategy.

Deserializing should be working the same way.

Maybe it is also sufficient to send an enum (int) that determines the object state.

| improve this answer | | | | |

Design a class system.Every class has a method

char *toString(struct Obj *self);

You can only use sprintf to serialize your data to a string buffer.

I like to use the JSON format to serialize, because this format is easy to read, parse and combine.

| improve this answer | | | | |

Your Answer

