Question

I've been working into a small game just for learning. The intent of the game is that it is going to be online, but I have some trouble on how to serialize the commands sent from server to client. There is a lot of different commands that can be sent, and handling this manually is driving me insane. At the moment I'm using lots of 'ifs' to do this, but I hope there is a Design Pattern that helps. I would like to unpack the message in different kinds of objects so I could get them from some kind of queue and treat them efficiently... But I would like to do it partially or completely automatic.

Is there a good practice to solve this kind of problem? It would be good if it was efficient too.

Thanks in advance.

PS: Although this is a conceptual question, I'm using C++, so some specific solution would be fine too.

Was it helpful?

Solution

Try a Factory pattern. Something along these lines is a useful factory model.

Make a base class that provides methods for serialising and deserialising data from a stream, and register your derived types by name or some other identifier with the factory.

You can package up a command in a bundle with a header that tells the receiver what type to create. When you read a command, you ask the factory to create the correct type. Then returned type can then be called to deserialise its data.

Here, I'm assuming that some commands have extra data.

Once you have popped the command out of the queue for processing, you can call its 'Execute' method.

OTHER TIPS

There is a design pattern called "actors", which might be what you want. Features:

  1. natual and simplified concurrency model.

  2. could be used together with pattern matching over messages (eliminate "ifs").

Language 'scala' provides good support for this design pattern and perfectly meet your need. However, I don't know whether there is similar solution in C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top