当JVM加载LazyLoadedSingleton类时,由于该类没有static属性,所以加载完成后便即刻返回。只有第一次调用getIndtance()方法时,JVM才会加载LazyHolder类,由于它包含一个static属性singletonInstance,所以会首先初始化这个变量。
public class LazyLoadedSingleton{
private LazyLoadedSingleton(){
}
private static class LazyHolder{
private static final LazyLoadedSingleton singletonInstance = new LazyLoadedSingleton();
}
public static LazyLoadedSingleton getInstance(){
return LazyHolder.singletonInstance;
}
}
本文介绍了懒汉式单例模式的实现方式。在这种模式下,JVM在加载LazyLoadedSingleton类时不会立即实例化对象,只有在首次调用getInstance()方法时才加载LazyHolder并初始化静态成员变量singletonInstance。
1059

被折叠的 条评论
为什么被折叠?



