5 ms·
Without starting a flame war, I use a few singletons in my game and I dont understand why it is a problem. The instantiation of the game, an object that manage
by jason_slack 13y ago
Without starting a flame war, I use a few singletons in my game and I dont understand why it is a problem.
The instantiation of the game, an object that manages layers, HUDS, Preferences and saving game data (it is done in a separate thread).
I have also worked places where literally every class is a singleton (practically, not really all) and to avoid the xxx->getInstance()->yyy->getInstance()...... They would use some Defines to shorten typing it all.
- pmelendez 13y ago> xxx->getInstance()->yyy->getInstance() That is weird... wouldn't you just do yyy::getInstance() directly? The whole point of singletons is being global right?
- jason_slack 13y agoWell I think that yyy is a private member variable inside of xxx so maybe that is why the did that? Like: #define GAMELAYERINSTANCE _dir->Instance()->getGameScene()->Instance()->getGameLayerObject()->Instance()
- gohrt 13y agoYou mean getGameSceneClass() and getGameLayerClass(), yes? As in Dependency Injection? object->getInstance() makes no sense, you already have the object!
- jason_slack 13y agoI may be reading this weird. object->getInstance makes no sense? You mean if object is a private member variable? So class _dir contains object as a member variable. _dir->Instance(), already has access to object without doing _dir_Instance()->object->Instance() as an example...?
- pmelendez 13y ago> object->getInstance makes no sense? If getInstance returns an instance of object class, and object is an instance itself, then it doesn't make sense or it is not a singleton. You can think it like this: if object class has one unique instance, then object == object->getInstance(), so in your case either object != object->getInstance and they are from the same class (hence it is not a singleton) or they are from different classes (once again then, it is not a singleton).
- mattfenwick 13y agoThe major problem they cause IMHO is coupling. Some examples of how this has bitten me: - can't instantiate the singleton differently. - program does task A, then task B, and both use the singleton; now you have to worry about the state that the singleton was left in after completing task A. - can't create multiple, separate instances. - can't easily mock for testing. - can't easily swap out with a different implementation. I've run into each of these problems, and I can never see any value provided by the singleton. All the pattern does is reduce the flexibility, adaptability, and usefulness of the code it's applied to (at least in my experience -- I'm not implying that it's always or necessarily so).
- jason_slack 13y agoI definitely agree that there are places where a singleton just is in no way the correct option. You have laid out some good examples here.