Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good programming to have lots of singleton classes in a project?

Tags:

c++

singleton

I have a few classes in a project that should be created only once.

What is the best way to do that?,

  1. They can be created as static object.
  2. Can be created as singleton
  3. Can be created as global.

What is the best design pattern to implement this?

I am thinking of creating all classes as singleton, but that would create lot of singletons. Is it good programming practice to have lot of singletons?

What are the pros and cons for using singletons?

like image 284
anand Avatar asked Nov 28 '22 00:11

anand


2 Answers

Take a look at Steve Yegge's blog post about this - Singleton Considered Stupid

like image 115
David Hodgson Avatar answered Dec 16 '22 00:12

David Hodgson


If they only need to be created once, that doesn't mandate they should be singletons.

  • If X is a singleton, it's implied there is one instance.
  • If X has one instance, that doesn't mean it should be a singleton.

Use a singleton if you require there be only one instance of the class, and that it be globally accessible. In your case, simply only needing one isn't reason enough. Globals are bad, singletons are glorified globals.

Most often, you don't need them. You'll see it a lot in bad code because of the very mentality: I only need one, that must mean I should make it singleton! (Wrong) For example, I've finished the technical design of the most powerful game engine I've ever done to date. It has 2 singletons, for memory and threading. A very large project, and I only have two!

More context would help us give you better information.

like image 36
GManNickG Avatar answered Dec 15 '22 22:12

GManNickG