开发者

Consequences of Singletons

So I just delved into the Singleton classes and yes, I find them quite helpful. I use my singletons mostly for data storage for multiple targets (views, tables etc.). That being said, I can already see myself going to implement a lot of singletons in my project.

But can a lot of singletons have a negative impact? From开发者_开发技巧 what I've read about singletons is that you create one instance for each of them in a proces. Other class instances get released (assuming they get released properly) from memory, then should singletons be released too?

So to narrow it down to one question: Is it harmful to have a lot of singletons?


Singletons don't scale. No matter what you think should be a singleton, when your system gets bigger, it turns out you needed more than one.

If you NEVER need more than one, a singleton is fine. However, as systems scale, you typically need more than one of anything within its own context.

Singletons are merely another way to say "global". It's not bad, but generally, it's not a good idea for systems that evolve and grow in complexity.


From GOF Book:

The Singleton pattern has several benefits:

  1. Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it.

  2. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.

  3. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.

  4. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change.

  5. More flexible than class operations. Another way to package a singleton's functionality is to useThe Singleton class can be subclassed. class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance ofclass. Moreover, static member functions in C++ are never virtual, so subclasses can't override them polymorphically.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜