繁体   English   中英

为什么我不能直接访问singleton实例? [复制]

[英]Why can't I get the singleton instance by accessing it directly? [duplicate]

例如:

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

    // Private constructor suppresses
    // default public constructor
    private Singleton() {};

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

为什么我不能将INSTANCE设置为公共,并通过Singleton.INSTANCE访问它? 它会导致什么?

从技术上讲,您可以并且在此代码中,它不会产生任何影响 - 它的行为将相同。

我们一般使用 getter 的原因是:

  • 一个好习惯——人们会惊讶地看到你直接访问一个变量
  • 灵活性——如果你在调用getter的代码周围有一百个地方,那么改变方法行为就很容易了(比如每次都返回new Singleton()而不是访问static变量)。 如果那一百个地方直接访问变量,那就不那么容易了。

Because its good practice to encapsulate your instance in order to avoid boiler plate code and in that case you need to use static block to initialize your object which is better if you initialize your object when needed (lazy load) may be benefit of your memory usage .

从技术上讲,您可以将Singleton.INSTANCE公开,因为它是final However, from the perspective of the user of your API, it is not obvious that Singleton.INSTANCE is final without looking at the contents of the Singleton class, and a user might be tempted to try to reassign Singleton.INSTANCE from a different class.

使Singleton.INSTANCE只能通过Singleton.getInstance()访问,这对每个人来说都很明显,无法重新分配变量。

暂无
暂无

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

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