[英]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 的原因是:
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.