首页 > 解决方案 > 在多级继承的情况下,如何编写一个类以将对象创建限制为一次?

问题描述

假设我们有三个类 A、B 和 C

class A{
    
    A(){
        System.out.println("A");
    }
    
}

class B extends A{
    
    B(){
        //super
        System.out.println("B");
    }
}

class C extends B{
    
    C(){
        //super
        System.out.println("C");
    }
}

public class Main{
    
    public static void main(String[] args){
        
        C c = new C(); // This will print ABC and that is fine

        C c' = new C(); // Should not be allowed
    }
}

我想提出一些逻辑,以便在创建 c 之后不允许 C c' = new C() 。任何建议将不胜感激。我在面试中被问到这个问题,面试官暗示说“你可以用 super 做点什么”。但我没有回答。

标签: java

解决方案


看起来你想要单例模式。

class C extends B {
  
  private static class SingletonHolder {
    static final C SINGLETON = new C();
  }
  
  private C() {
    super();
    System.out.print("C");
  }

  public static C getInstance() {
    return SingletonHolder.SINGLETON;
  }
}

这样,它只会打印ABC一次,第一次getInstance被调用,因为SingletonHolder只会在你调用时加载getInstance

然后你可以像这样使用它:

C c = C.getInstance();

如果你想要一个运行时异常,那么你可以保留一个静态布尔字段来C告诉你C的构造函数是否已经被调用,如果有人试图再次实例化它,则抛出一个异常。但是,我怀疑这就是面试官想要的。


推荐阅读