开发者

When should I use a singleton class in C++?

From a beginning C++ user's point of view the only reason I would see a singleton class useful开发者_高级运维 is similar to when I want to use a static variable. Do you guys know when its most appropriate to use a singleton class?


The only time you should use a singleton is in the rare case where it is VITAL that there only ever be one of these objects. This simply doesn't come up nearly as often as you might think.

Quite often it's more than sufficient to just make a single instance of the class in question, but not put in all the machinery required to enforce the uniqueness of the object.

Every time I've used a singleton (or found one in the codebase I work with) I've ended up removing it because I needed to change the behavior, and the singleton machinery got in the way. I've yet to see a case in our code (payment processing) where a singleton actually made sense. I've got more than a few cases where I've only got one instance of a particular class, but none where enforcing that through the singleton pattern was necessary or helpful.


When you really need it, you'll know.

That might never happen.

When you think you want it, you're probably wrong.


I can't think of any instance where using a singleton class is appropriate.

In Java, they're mostly for organization. In C++, however, you should use namespaces instead.


I used to create singletons with global static accessors: UserRegistry::getInstance(). Now, in the Dependency Injection era, I just use a registry. Helps with unit testing, too.


Singleton classes are glorified global variables. Use only when absolutely necessary, i.e. when an object has only a single instance throughout the scope of your implementation.


There was a thread on Hacker News yesterday talking about when it's NOT a good idea to use a singleton. There were several ideas there about when it IS a good idea to use a singleton (global configuration data, session management in webserver apps) but for every justification for singletons there are also good arguments as to why that's not a good idea. http://news.ycombinator.com/item?id=2743894


I can think of several reasons in the field of game development that having a class implemented as a singleton is absolutely required:

Physics Engines, Sprite Handlers, Gravity Handlers (if separate from Physics Engines), Input Parsers, etc.


everything solvable without singleton. but i found myself using it to better control initialization and destructions of an object like graphic context. or when using state machine to better control state transitions. also, in (rare) cases when there's a system resource that's limited to 1 unit (e.g. console), and in when multithreading to prevent condition race. (https://refactoring.guru/design-patterns/singleton/cpp/example)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜