Advantage of Singleton Interface Implementation

On some blogs, I read that singleton interferes with testing because it causes high coupling , and mocks cannot be replaced instead, so the solution is to implement the interface and pass it in arguments. I have no links to blogs, and I will attach them as soon as I find them. But due to the static getInstance() method, this is not possible.

So, is there an advantage to implementing an interface in a Singleton template?

 public interface SingletonInterface{ //some methods } public class Singleton1 implements SingletonInterface{ //Usual singleton methods } 
+4
source share
1 answer

But due to the static getInstance () method, this will not be possible.

No, quite the opposite. The fact is that only a very limited amount of code should know that this is a singleton. Other code may just use the interface, and you can have different implementations for testing and even change the production implementation later, so as not to be a single without changing it at all.

 public void foo(SingletonInterface x) { // This code doesn't know it a singleton. You can create fakes for testing. } ... // This code *does* know it a singleton. Boo! Gradually refactor away... foo(Singleton1.getInstance()); 
+7
source

Source: https://habr.com/ru/post/1494663/


All Articles