2 ms·
This reminds me of a design question I recently faced when building a simple multi-player game. The idea was pretty standard; The server sent events (player die
by foobarz24 13y ago
This reminds me of a design question I recently faced when building a simple multi-player game. The idea was pretty standard; The server sent events (player dies, player moves to pos, etc.) to its clients over a TCP socket. When programming the client in Java (for Android) I wanted a clean way to update the world based on the event type. In Haskell I would have done something like
data Event = PlayerDied Player Reason | PlayerMove Player Coords | ...
and use pattern matching on the event type. In C I would have used a combination of unions and structs with an event type. But how to do that in Java? I ended up with
interface Event {
public update(Game g);
}
and used e.g.
class DeathEvent implements Event {
DeathEvent(String player, String reason) { ... }
update(Game g) {
g.killPlayer(player, reason);
}
}
Combined with a parsing function (public Event parse(String line) {...}) I could read from the socket and update the game in a convenient way, but to be fair I used that mostly because Java guys discourage you to use instanceof although it seemed clearer.
So is this the preferred way to do something like this? I think "they" (the OOP warriors) call this the Visitor pattern. However I really find the data-type encapsulation in Haskell and other languages (in Python a tuple (type, object) would do) superior. But maybe my Java just got rusty.