单例模式之饿汉式
在类加载时就初始化一个类对象,使用静态加载,但是在类加载时就实例化对象,单例对象较大的时候会影响系统加载速度。
public class Singleton {
private Singleton() {
System.out.println("This is constructor.");
}
private static Singleton instance = new Singleton();
public static Singleton getInstance () {
return instance;
}
public static void main(String[] args) {
Singleton.getInstance();
}
}
延迟加载的singleton
只有在访问到单例对象的时候才去检查和实例化单例对象,满足延迟加载,但多线程访问时需要加线程同步,影响访问效率
public class LazySingleton {
private LazySingleton() {}
private static LazySingleton instance ;
public synchronized static LazySingleton getInstance () { //对于多线程访问的需加synchronized
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
使用静态内部类来作为singleton的容器
既能延迟加载,又能保证线程安全
public class StaticSingleton {
private StaticSingleton() {}
private static class SingletonHolder { //私有内部类在StaticSingleton 加载时,不初始化
private static StaticSingleton instance = new StaticSingleton();
}
public static StaticSingleton getInstance () {
return SingletonHolder.instance;
}
}