I saw this while using picocontainer. They say you have to avoid singletons.
because the Singleton pattern makes it almost impossible for the class (and possibly all other classes which depend on it) to be testable. It’s very hard to subclass, or to create a mock object for a Singleton class.
But if you absolutely need it , Is there a workaround for the testing and subclassing issue ?
What makes it hard to test singletons is the code enforcing their singleton-ness (meaning the
public static MySingleton getInstance() {...}boilerplate). Using an inversion-of-control container, like Picocontainer or Guice or Spring, removes that concern from the object, so now:It can be instantiated and have collaborators plugged into it in tests without a problem.
The code calling a singleton doesn’t have to know what class it is looking up (which it would need to know if it had to call a static method).
I interpret the advice on picocontainer’s website as being similar to this. What they are telling you is, let our container manage the scope of your components for you, don’t hard-wire the scope-enforcing code into them.