在我的Java学习之旅,我碰到代码来了,是被标记有以下几点:没有必要延迟初始化,因为类没有状态
/**
* Singleton instance - no need to lazy init as the class holds no state.
*/
public static final SuperParentMarshaller instance = new SuperParentMarshaller();
这是什么意思?这是什么类?这是目的?
预先感谢您。
在我的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;
}
}
谢谢阿米特。很好的解释。 –
单例是为了确保在应用程序中存在一个,并且只有一个该对象的实例。例如,当确保只有一个音频类实例时,它可以派上用场,因此不会有两个实例要求音频设备播放两个不同的东西。
尽管在实践中,单身人士并没有太多的使用,但如果你遇到过单身人士,那么知道它存在就很方便。
初始化方法比用于确保只能创建一个实例。有几种方法可以确保这一点,如果您不保护实例被创建不止一次,则2个线程可以同时进入该类,并且最终可以获得该类的两个实例。这会违背你想要达到的目标。
的可能的复制http://stackoverflow.com/questions/3192095/where-exactly-the-singleton-pattern-is-used-in-real-应用程序 –
你问什么是单身人士吗?还是你问懒惰和渴望初始化之间的区别?你应该能够找到堆栈溢出这两个问题的答案。 –
我不明白上面陈述背后的逻辑是什么以及如何使用它。在类SuperParentMarshaller中,有一个变量被初始化为'public static final SuperParentMarshaller instance = new SuperParentMarshaller();'这有助于什么?我真的想了解为什么可以用这种方式编码的目的。 –