0

Possible Duplicate:
What is so bad about Singletons?
Singleton Design Pattern: Pitfalls

I hear a lot of this but din't find firm reason for it.

Avoid the singleton anti-pattern and replace it with DI.

but, why?

Community
  • 1
  • 1
Amandeep Jiddewar
  • 1,632
  • 1
  • 13
  • 27

1 Answers1

4

Stateful singletons are much more difficult to unit test.

I use stateless singletons which I don't see a problem with.

Since singletons can implement interfaces, they can be passed using dependency injection (and should be passed as such where possible)

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
  • 4
    If the singleton is stateless then why have a singleton at all rather than a collection of static methods? – Servy Aug 22 '12 at 15:03
  • 4
    There's no such thing as a "stateless singleton." – Robert Harvey Aug 22 '12 at 15:03
  • 1
    A stateless singleton can implement an interface. Say you have a `Marshaller` interface which functionally turns an Object into a `byte[]` and back again. You want to be able to pass different strategies via DI which means you have to have an instance to pass. There is any number of implementations for this each potentially with their own class, but you only need one instance if they are stateless. – Peter Lawrey Aug 22 '12 at 15:06
  • 4
    Sounds like a case where it would be better to have a delegate to provide the function that turns an object into a byte, that way it could be either instanced or static (assuming you have control over both the using and calling code). – Servy Aug 22 '12 at 15:08
  • 1
    The problem with using static method directly is that you allow only one way of marshalling your data when there are potentially dozens of way of doing it. DI should allow you to change how you want to Marshal your data and allow others to provide their own means. This requires an instance which implements a common interface, but if that instance is stateless you only ever need one. – Peter Lawrey Aug 22 '12 at 15:11
  • 1
    Another example I have is a TimeService which gives the time in micro-seconds. There is a simple one which uses currentTimeMillis(), one which uses nanoTime() as well and third which is progammable (but not stateless) – Peter Lawrey Aug 22 '12 at 15:13
  • If the object doesn't hold any state, does it really matter whether you have one instance or many servicing your interfaces? There's negligible overhead, since all instances share the same class code. – Robert Harvey Aug 22 '12 at 17:12
  • 1
    @RobertHarvey It doesn't matter except it makes it clear that multiple instances are not needed. Having multiple instances can imply this is done for a reason. – Peter Lawrey Aug 22 '12 at 18:54
  • Peter is right, even if there's no state, if multiple instances are not needed, why create those multiple instances? E.g. String.Empty is a singleton. Create enough empty strings and at some point there will be a noticeable performance difference. – Wout Nov 23 '12 at 23:42