Singleton实现接口的优势

Nar*_*hai 4 java singleton design-patterns interface

我在一些博客中读到单例妨碍测试,因为它导致高耦合,而模拟不能代替它,所以解决方案是实现一个接口并在参数中传递它.我没有博客链接,一旦找到它就会附上它.但由于static getInstance()方法不可能.

那么在Singleton Pattern中实现接口有什么优势吗?

public interface SingletonInterface{

   //some methods
}

public class Singleton1 implements SingletonInterface{

   //Usual singleton methods 
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

但是由于静态的getInstance()方法是不可能的.

不,完全相反.关键是只有非常有限的代码需要知道它是一个单例.其他代码可以只使用该接口,您可以使用不同的实现进行测试,甚至可以在以后更改生产实现而不是单例,而不必更改它.

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());
Run Code Online (Sandbox Code Playgroud)