Many times i have a class that should have only 1 instance. Is the best practice is to use singleton?
-
That's what singleton is for. The question is whether you `need` to have a single instance or just happened to right some code that uses only one instance and doesn't require for more. The first case is a singleton, for the second a simple class is enough. – svz Aug 27 '13 at 11:17
-
Singleton is the definition of what you describe. – rocketboy Aug 27 '13 at 11:18
-
Absolutely not. If you're using lots of singletons you're not designing your application correctly. – Hot Licks Aug 27 '13 at 11:31
6 Answers
Singletons are global state. They should be used only when it's really necessary, for the same reason that your code shouldn't have a ton of global variables.
"Should have" is the operative question. If the system doesn't care how many instances there are, don't make it a singleton. Only if the system truly requires that there be only one instance should you be thinking singleton.

- 13,209
- 3
- 37
- 52
Another pattern you can use is a factory method. The advantage here is that the factory may decide to return the same instance every time or a new instance. This will impose less limitations if you someday choose you don't want just a single instance, but let's say for example - a single instance per thread.

- 3,897
- 5
- 31
- 42
-
2
-
-
1I'm not saying you do it, but I very often see people commit to singletons even though they're using the static factory. Totally confuses me. – Eric Stein Aug 27 '13 at 11:39
-
The best practice is to use a dependency injection framework like Spring or Guice. Many people think that Singleton is rather an antipattern than a good practice.

- 133,369
- 30
- 199
- 275
As per my experience , In most cases (atleast in my case :)) a singleton is equivalent to a class consisting only of static attributes
and methods
.
The singleton pattern
is a simpler way of slowing down the system by implementing syncronization
.
Don't go for it unless you need it.
If you are ok with multiple instances
go for it,Other wise go for dependency injection
.
A good article here read few days ago.

- 120,458
- 37
- 198
- 307
An additional answer I've just found on other sources.
Singleton is good to use when you should access the same one instance from multiple parts of the code.
Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.
For More Click here

- 6,357
- 5
- 40
- 55