-2

evil singletons

Should I avoid using the singleton pattern?

Edit: Okay I wasn't expecting to get closed down.

I guess I should clarify a bit, I have been using singletons for:

1)storing a connection string to a database, or the role of the current user.

2) time consuming data to retrieve from a remote data server - it has a very slow connection.

Brad
  • 20,302
  • 36
  • 84
  • 102
  • 2
    Once you use Dependency Injection there is rarely a need for the classical Singleton pattern. You just tell your container to always give you the same instance. This solves some of the problems of a singleton(At a glance it solves all problems mentioned in that article). The inherent problem of global mutable state obviously remains in some(less severe) form. – CodesInChaos Jul 24 '11 at 20:59
  • Effectively a duplicate of http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – TrueWill Jul 24 '11 at 21:01
  • 1
    Neither of your examples needs to enforce that they are a singleton. Create an interface for it (Say `IRetrieveDataFromServer`) and then let DI pass it into the constructor of your type. – CodesInChaos Jul 24 '11 at 21:02
  • @CodeInChaos - thanks for the tips, I'll look for some examples. – Brad Jul 24 '11 at 21:05

2 Answers2

2

The singleton pattern is not evil in itself, but if you overuse it, you will notice that it's not a solution for everything.

Like any pattern it has its use, but you should only use it when you need it, not everywhere that you possibly can.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Actually, you don't need to overuse it. You can to use it and wait for it to become evil. – vgru Jul 24 '11 at 21:51
0

You should if you agree with Google.

Nowadays I think Singleton would be the pattern most likely to be expunged from the Gang of Four book.

A fan? Really?

duffymo
  • 305,152
  • 44
  • 369
  • 561