3

Possible Duplicate:
On Design Patterns: When to use the Singleton?

Hi Just wondering what are good candidates for singleton?

Just reading about it and wondering if sometimes I have misused it.

Generally speaking when would you use a singleton?

thanks a lot

Community
  • 1
  • 1
user9969
  • 14,468
  • 37
  • 101
  • 168

1 Answers1

0

Basically, whenever I need a class but am not sure I will need a singleton pattern, I code to the singleton interface, but let the implementing class determine whether or not to return a single instance or a new instance. That way, calling classes don't have to worry about changing if the move to singleton (or the move away from singleton) should occur.

Places I've used this successfully is on my repositories. But I always preface every singleton answer with a 'Make sure you pay attention to thread-safety, whichever way you go'. Sometimes weird things can happen in a multi-threaded environment when dealing with a singleton.

Josh
  • 9,475
  • 11
  • 53
  • 99
  • Another fun thing to watch out for is using an 'Instance' property to construct the Singleton, if the constructor has any side effects. If you happen to hover over the Instance property while in the debugger, it's possible to trigger some of the side effects of the singleton construction without actually setting the instance field, resulting in double invocation of the side effects when you step through and long, vexing debugging sessions. – Dan Bryant May 23 '11 at 20:08
  • "whenever I need a class but am not sure I will need a singleton pattern, I code to the singleton interface, but let the implementing class determine whether or not to return a single instance or a new instance": This violates YAGNI, and definitely reminds me of [The mating call of the loser](http://blogs.msdn.com/b/oldnewthing/archive/2009/02/13/9416485.aspx) ;-) – Dirk Vollmar May 23 '11 at 20:27
  • ...(continued) "When given a choice between two architectures, some people say that you should give users a checkbox to select which one should be used. That is the ultimate cowardly answer. You can't decide between two fundamentally different approaches, and instead of picking one, you say "Let's do both!", thereby creating triple, perhaps quadruple the work compared to just choosing one or the other." – Dirk Vollmar May 23 '11 at 20:28