1

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?

2
  • 1
    Thanks, for editing and links to questions :) Commented Aug 22, 2012 at 15:03
  • This link might give you some good pointers. Commented Oct 25, 2016 at 6:32

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

9 Comments

If the singleton is stateless then why have a singleton at all rather than a collection of static methods?
There's no such thing as a "stateless singleton."
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.
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).
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.