在我的java学习之旅中,我遇到了带有以下注释的代码:
/**
* Singleton instance - no need to lazy init as the class holds no state.
*/
public static final SuperParentMarshaller instance = new SuperParentMarshaller ();
这是什么意思?这会是一堂什么样的课呢?其目的是?
提前谢谢您。
最佳答案
这是您提到的急切初始化。在请求该对象之前,该对象已经初始化。使其变得惰性意味着该对象将在第一次调用时进行初始化。这是一个单一的设计模式。整个应用程序中只会有一个该类的对象。
// eager loading of INSTANCE
public class Singleton
{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
延迟初始化是:
// lazy initialization
public class Singleton
{
//initailzed during class loading
private static final Singleton INSTANCE;
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
// object will be initialized on it's first call.
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
}
关于java - 由于类没有状态,因此无需延迟初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501474/