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
}
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With