设计模式--单例模式
今细阅单例,收获纷多,暂此记下,日后回首。
1、饿汉单例
JVM运行时则加载该单例(最常用),不用考虑线程安全等问题
public class HungrySingleton { public class EagerSingleton { private static final EagerSingleton eagerSingleton = new EagerSingleton(); private EagerSingleton(){ } public static EagerSingleton getInstance() { return eagerSingleton; } }
public class Singleton { // 懒汉式单例 private static Singleton singleton = null; private Singleton() { } public static Singleton getInstance() { //Double-Check Locking 保证线程安全 if (singleton == null) { synchronized (Singleton.class) { if(singleton == null) { singleton = new Singleton(); } } } return singleton; } }
public class Singleton { private Singleton() {} private static class SingletonHolder { static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; }}