Question

I'm working on a small, turn-based, two-player game written in C++ on top of Cocos2d-x. I have a full REST API established, and I am looking at designs for implementing the client side.

When a user opens the game, she will be displayed a list of her currently active games. This list should be cached, but a refresh must be attempted before the list is displayed. Whenever she taps on one of the games in that list, the game will be loaded. Thus, the game states will also have to be cached. Nothing unusual here.

Now, I'd like to avoid constructing url's and using the cocos2d-x HttpRequest and HttpClient classes from client code. Moreover, the code for maintaining a list of games, refreshing said list, fetching a certain game state, and pushing game state to the server could easily fit into a Singleton. Let's imagine we have such an object, and we call it GameLobby in lack of a better name.

In my mind, these related actions call for a single, encapsulating class instance, so Singleton seems to fit the bill. Passing a reference to a GameLobby around just doesn't make a lot of sense to me. It would basically mean that I have to pass it to every cocos2d::Scene in my game that needs to know anything about the state of the active games, fetching game state from the server, etc. However, as I've come to understand, the Singleton pattern has become more of an anti-pattern over the years.

Would I be better of using a Service Locator? What about other patterns - are there any relevant that comes to mind?

Was it helpful?

Solution

After a good nights sleep, it occurred to me that I don't want to create a monolithic singleton. Not necessarily because it is a singleton, the emphasis is on monolithic. Having a single class implement all the game list and individual game state transaction logic feels like a serious violation of the single responsibility principle.

So, here's a quick and dirty class diagram of what I'd like to implement:

enter image description here

GameListScene will be responsible for holding a GameList instance. This is the only scene in the game that will expose the list to the user, and so there's no current requirement that says it has to be passed around. The GameScene instance is going to be where the action takes place. Both GameList and Game will be responsible for talking to the REST API. One of my reasons for going with the singleton, was to hide the url and http stuff from the client (GameListScene and GameScene). In order to accomplish this, I've decided to let them inherit from RESTClient. This way, I can keep at least keep the http stuff hidden while not repeating myself.

The bottom line is: I've got more classes with this design, but hopefully it'll prove to be a cleaner and easier to maintain.

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