Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of Singleton implementing an interface

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 
}
like image 643
Narendra Pathai Avatar asked Mar 22 '23 22:03

Narendra Pathai


1 Answers

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());
like image 120
Jon Skeet Avatar answered Apr 01 '23 08:04

Jon Skeet