[英]Static instance variable references instance of the class
Can I let a static field of a class keep a reference to an instance of itself? 我可以让类的静态字段保持对其自身实例的引用吗? If so, will it keep alive in the jvm without anyone else keeping a reference? 如果是这样,它会在jvm中保持活着而没有其他人保留引用吗?
public class StatTest {
private static StatTest statTest;
public static StatTest getStatTest () {
if (statTest== null) {
statTest= new StatTest ();
statTest.init();
}
return statTest;
}
private StatTest() { }
}
是的,这是Singleton设计模式的概念!
This is one way to create a singleton of a class. 这是创建类的单例的一种方法。
So to answer your question: 所以回答你的问题:
getStatTest()
method will return that instance. 对getStatTest()
方法的所有引用都将返回该实例。 When using this method for a singleton, the method is mostly called getInstance()
=) 将此方法用于单例时,该方法通常称为getInstance()
=)
will it keep alive in the jvm without anyone else keeping a reference? 如果没有其他人保留参考,它会在jvm中保持活力吗?
Yes, as long as the class itself is not eligible for garbage collection (which can only happen if you use a custom classloader). 是的,只要类本身不符合垃圾收集条件(只有在使用自定义类加载器时才会发生)。
Congrats. 恭喜。 You've reinvented the singleton. 你重塑了单身人士。 http://en.wikipedia.org/wiki/Singleton_pattern http://en.wikipedia.org/wiki/Singleton_pattern
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.