大话设计模式之单例模式
单例模式
一、饿汉式
在类初始化时,已经自行实例化
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
二、懒汉式
在首次调用的时候实例化
public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (null == instance) { instance = new Singleton(); } return instance; } }
三、双重检测
public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (null == instance) { synchronized (Singleton.class){ if(null == instance){ instance = new Singleton(); } } } return instance; } }
四、initialization on demand holder
public class Singleton { private Singleton() { } public static class Holder{ static Singleton instance = new Singleton(); } public static Singleton getInstance() { return Holder.instance; } }