线程安全的单例类
单例模式中,有两种实现,一种是饥饿模式,另一种是懒汉模式。
饥饿模式的实现:
public final class EagerSingleton { private static EagerSingleton instance = new EagerSingleton(); private EagerSingleton(){ } public static EagerSingleton getSingleInstance(){ return instance; } } public final class LazySingleton { private static LazySingleton instance = null; private LazySingleton(){ } public static LazySingleton getSingleInstance(){ if(null == instance ) { instance = new LazySingleton();}eturn instance; } } public final class LazySingleton { private static LazySingleton instance = null; private LazySingleton(){ } public static synchronized LazySingleton getSingleInstance(){ if(null == instance ) { instance = new LazySingleton();}eturn instance; } } public final class DoubleCheckedSingleton { private static DoubleCheckedSingleton instance = null; private DoubleCheckedSingleton(){ } public static DoubleCheckedSingleton getSingleInstance(){ if(instance == null ) { Synchronized(DoubleCheckedSingleton.class){ if(instance == null){ instance = new DoubleCheckedSingleton(); } }}return instance; } } public class Singleton { private static class SingletonHolder { public final static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } }