简体   繁体   English

Java,就像flliows一样,为什么程序的全局变量仅保留一个实例?

[英]java, as flliows,why does this global varaible of the program keep only an instance?

Could the uniqueeInstance have one and only one instance? 唯一实例可以只有一个实例吗?

public class A {

     private static A uniqueInstance = new A();

     private A() {}

     public static A getInstance() {
            return uniqueInstance;
     }
}

This is a Singleton pattern, it's purpose is to have only one possible instance for a class. 这是一个Singleton模式,其目的是为一个类仅创建一个可能的实例。

This is why you have a private constructor , so that no other class can attempt to instantiate it directly. 这就是为什么要使用私有构造函数的原因,因此没有其他类可以尝试直接实例化它。

Here are more elaborate thoughts for possible uses of a Singleton : 以下是有关Singleton可能用途的详细说明:

When to use the Singleton 何时使用Singleton

It is not guaranteed. 不保证。

By reflection you are easy to get more instances. 通过反思,您很容易获得更多实例。

The only way to guarantee that you have exactly one instance is to use an enum: 确保您只有一个实例的唯一方法是使用枚举:

enum Holder {

    INSTANCE;

    //Keep in Mind of A you may still have more instances. if you want to have the
    //guarantee to have only one instance you may need merge the whole class
    //into an enum (which may not be possible)
    public A uniqueInstance = new A();    
}

Other ways like throwing an exception in the constructor are generally also possible. 通常也可以使用其他方法,例如在构造函数中引发异常。 But not completely secure since there are ways to create an Object without calling any constructor. 但是并不是完全安全的,因为有多种方法可以创建对象而不调用任何构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM