开发者

Am I using Singleton approach correctly? (iOS game dev't)

I开发者_如何学C just got into using singletons and I just want to evaluate if I'm using it correctly. I've read that singletons are evil. I've only started with game dev't so things like unit testing and multithreading doesn't reach me yet.

I separated the logic of my game into different modules. Each module has a singleton and non-singleton classes (eg. data model). I'm using the singleton as a mediator so it can interact with other modules. This allows me to work with other people since it's in manageable pieces and I only need to expose the helper methods of my singleton. He doesn't need to know how I implemented it.

Am I doing the right thing?

Examples:

  • In a traditional japanese SRPG game (like FFTactics), the cells/grid for the tilemap has its own module. The character interacts with the singleton of this module.

  • All my sprites are generated by an AssetManager (a singleton) which autoscales the sprite depending on the resolution-availability and resolution of the device. This is done just by a calling a method in the singleton.


I definitely don't agree that singletons are evil. They are sometimes overused perhaps but on some occasions are just perfect for the job. In some applications it makes sense to have some kind of general data manager. The singleton pattern is used extensively in the SDK itself (app delegates, shared managers, default centers and so on). Most often these are not "pure" singletons, as in you can access a shared instance but can also create new instances if necessary.

The question you need to ask yourself is whether it would be useful to have access to a single instance of a data manager from anywhere at anytime, if it isn't then a singleton is probably not needed. If you are going to be using singletons in multi-threaded environments however, you do need to worry about race conditions (can one thread modify a resource while another is accessing it), the documentation has good explanations on how best to achieve this in Cocoa.


You could easily do that with an instance too.

Let's say you have a GameMap class and a Tile class. The GameMap represents a 2 dimension grid of Tile objects. (This is your FFTactics example).

GameMap *gameMap = [[GameMap alloc] init];
NSArray *theTiles = gameMap.tiles;

The instance of the GameMap owns the grid of tiles, and creates the tiles when the game map is created. No singleton needed.

You may say "but I only have one GameMap at a time, what's the big deal?". What about loading saved games, or loading new levels? Well that becomes as easy as:

// In whatever class object owns the game map
self.gameMap = [[GameMap alloc] initWithSaveData:saveData];

In conclusion, create an instance of a class that has code to manage other instances of things. Keep as little global as possible and your code will be more scalable and maintainable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜