java - 在多级继承的情况下,如何编写一个类以将对象创建限制为一次?
问题描述
假设我们有三个类 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 做点什么”。但我没有回答。
解决方案
看起来你想要单例模式。
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
的构造函数是否已经被调用,如果有人试图再次实例化它,则抛出一个异常。但是,我怀疑这就是面试官想要的。
推荐阅读
- javascript - Vue JS 插槽[name$1].every 不是函数
- python - 无法有条件地删除某些 csv 文件
- javascript - 如何处理reactjs中输入的更改?
- wordpress - 定制的 WordPress Dashboard 会在 WP 版本更新后保留吗?
- php - PHPUNIT 模拟方法接受任何参数
- angular - 将组件添加到多个页面。错误 | 离子 4
- python - “NoneType”的对象没有 len() - 错误
- html - 从已经修复的容器框中取出元素
- c - 如何将字符串转换为没有空格的整数?
- java - Java write(str.getBytes()) 与 writeBytes(str)