我们如何确保我们可以只创建一个 class 的实例?

How can we make sure that we can just create one instance of a class?

这是一道面试题。面试官向我展示了一个 class 个人和另一个 Class 社区。他想知道我们可以做些什么来确保在 Class 社区内,Class Person 的实例可以被调用一次。

我的方法是将一个布尔标志定义为一个全局变量,并检查 Class Person 的构造函数,如果标志值为 false,那么它将创建实例,否则 return错误。 This flag value is changed to true with the creation of the first instance Class Person.He 好像不是很满意的答案。

我知道这可能不是正确的做法。问题是,有没有办法使用 Class 定义或特定类型的 class?

您将使用 Singleton Pattern

public class Singleton {
    // Private constructor. Prevents instantiation from other classes.
    private Singleton() { }

    private static class SingletonHolder {
            private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
            return SingletonHolder.INSTANCE;
    }
}

或者将您的 class 创建为 enum 类型,使其成为真正的单例:

public enum Singleton {
    INSTANCE;
    public void execute (String arg) {
        // Perform operation here 
     }
}

我对所有单例命题都不太满意。

我也会这样回答。但真正的问题似乎是 "How to make the person unique within a community" 与 "How to make sur we can instanciate Person class once for all".

不同

如果那样的话,我会做一些完全不同的事情。

我会在 Community 中声明一组 Person 并覆盖 Person 的 equals 方法。

然后,在社区内,Person 将是唯一的,但 Person class 仍然可以为其他 Community 实例实例化。

public class Person{
   ...
    public Boolean equals(Object o){
       Person p = (Person) o;
       //you own equals logic
       return isEqual;
    }
    ...
}


public class Community{
    ...
    private Set<Person>;
    ...
}