方式一:适合单线程模式(不推荐)
public class Singleton { private static Singleton sg = new Singleton();; private Singleton() { } public static Singleton getInstance() { if (sg == null) { sg = new Singleton(); } return sg; } }
方式二:没有延迟加载(不推荐)
public class Singleton { private static Singleton sg = new Singleton();; private Singleton() { } public static Singleton getInstance() { return sg; } }
方式三:不适合高并发(不推荐)
public class Singleton { private static Singleton sg = new Singleton();; private Singleton() { } public static synchronized Singleton getInstance() { if (sg == null) { sg = new Singleton(); } return sg; } }
方式四:双重检测(推荐)
public class Singleton { private static Singleton sg; private Singleton() { } public static Singleton getInstance() { if (sg == null) { synchronized (Singleton.class) { if (sg == null) { // 双检索避免重复创建单例 sg = new Singleton(); } } } return sg; } }
方式五:推荐
public class Singleton { private Singleton() { } private static class SingletonHolder { private final static Singleton sg = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.sg; } }
学了Java多年,一直都是用方式一、方式二和方式三,今天才发现方式四,百度后才知道方式五。