Java 如何退回;模拟实施“;一个单身汉?

Java 如何退回;模拟实施“;一个单身汉?,java,Java,EJ说: 不可能用模拟实现代替单例 除非它实现了作为其“类型”的接口 那么,一个类,比如: public class TestSingleton implements TypeReturnable{ public static final TestSingleton INSTANCE = new TestSingleton(); private TestSingleton(){ } public static getInstance(){ return

EJ说:

不可能用模拟实现代替单例 除非它实现了作为其“类型”的接口

那么,一个类,比如:

 public class TestSingleton implements TypeReturnable{
    public static final TestSingleton INSTANCE = new TestSingleton();
    private TestSingleton(){
    }
    public static getInstance(){
    return this.INSTANCE;
    }
}


或者它是否包括在类的“构造”时将类型作为参数传递给类。我很困惑,当它实现作为其“类型”的接口时,如何替换实现?

提到的条件是

为了让您能够模仿单身汉,您需要:

  • 使单例实现一个接口或扩展一些超类(接口更干净)
    • 由于singleton有一个私有构造函数,因此不能扩展singleton类本身
  • 仅通过该接口使用该单例
    • i、 e.将其分配到变量中时,该变量必须是接口类型,而不是单例类型本身;调用方法时,仅调用接口的方法
  • 不要在整个代码中通过静态方法(即
    TestSingleton.getInstance()
    )访问singleton
    • 这种调用不能以使用mock而不是singleton的方式完成,必须用mock use替换
    • 您需要通过构造函数、参数、setter或使用依赖项注入框架传递singleton实例(或模拟singleton时的模拟实例)
    • 我会写

      public enum Singleton implements ISingleton {
          INSTANCE;
      }
      
      其中,通过依赖项注入传递单例

      MyTested mt = new MyTested(Singleton.INSTANCE);
      
      但是,要测试这一点,您可以执行以下操作

      ISongleton mockSingleton = createMock(ISingleton.class)
      MyTested mt = new MyTested(mockSingleton);
      
      我建议你不要吃太多

      • 可变单例(在构造期间传递可变对象)
      • 全局寻址单例(再次使用DI)
      TypeReturnable getType()
      
      ISongleton mockSingleton = createMock(ISingleton.class)
      MyTested mt = new MyTested(mockSingleton);