// 当 JVM 加载 LazyLoadedSingleton 类时,由于该类没有 static 属性,所以加载完成后便即可返回。只有第一次调用
// getInstance()方法时,JVM 才会加载 LazyHolder 类,由于它包含一个 static 属性
// singletonInstatnce,所以会首先初始化这个变量,这样即实现了一个既线程安全又支持延迟加载的单例模式。
public class LazyLoadedSingleton {
private LazyLoadedSingleton() {
}
private static class LazyHolder { // holds the singleton class
private static final LazyLoadedSingleton singletonInstatnce = new LazyLoadedSingleton();
}
public static LazyLoadedSingleton getInstance() {
return LazyHolder.singletonInstatnce;
}
}
附最简单的单例例子:
public class Singleton{
// static类型的类变量,只会赋值一次,保证线程安全
// 或将赋值语句放到静态代码块中,即 static {...}
private static Singleton instance = new Singleton();
// other fields...
// 构造方法为私有
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
// other methods
}
from:漫谈设计模式