3

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 Answers6

5

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.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52
4

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.

omer schleifer
  • 3,897
  • 5
  • 31
  • 42
2

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.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

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.

0

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.
enter image description here
For More Click here

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55