4

I read in some blogs that singleton hampers testing as it causes high coupling and mocks cannot be replaced in place of it, so the solution is to implement an interface and pass it around in arguments. I don't have links to blogs and will attach it as soon as I find it. But due to static getInstance() method that will not be possible.

So is there any advantage of implementing an interface in Singleton Pattern?

public interface SingletonInterface{

   //some methods
}

public class Singleton1 implements SingletonInterface{

   //Usual singleton methods 
}
Narendra Pathai
  • 38,384
  • 18
  • 73
  • 117
  • Mandatory disclaimer: http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – assylias Aug 01 '13 at 08:03
  • @assylias Yes I have read all posts I can find on Singleton. Thanks for the disclaimer though. – Narendra Pathai Aug 01 '13 at 08:05
  • This is my favourite: http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf‎ - it is more general but with a few good examples around singletons. – assylias Aug 01 '13 at 08:08
  • 1
    @assylias Yes I have followed his blog, as well as all videos on Youtube and my big favorite too. Misko's explanation is superb on the topic. – Narendra Pathai Aug 01 '13 at 08:09

1 Answers1

7

But due to static getInstance() method that will not be possible.

No, quite the reverse. The point is that only very limited amounts of code will need to know that it's a singleton. Other code can just use the interface, and you can have different implementations for testing, and even change the production implementation later not to be a singleton, without having to change it at all.

public void foo(SingletonInterface x) {
    // This code doesn't know it's a singleton. You can create fakes for testing.
}

...

// This code *does* know it's a singleton. Boo! Gradually refactor away...
foo(Singleton1.getInstance());
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929