1.懒汉式(内部类式)
/** * Created by pmx on 14-9-14. */ public class Singleton { private Singleton() {} public static Singleton getInstance() { return SingletonHolder.instance; } static class SingletonHolder { private static Singleton instance = new Singleton(); } }
2.懒汉式(同步)
/** * Created by pmx on 14-9-14. */ public class Singleton { private static Singleton singleton = null; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) singleton = new Singleton(); } } return singleton; } }
时间: 2024-10-02 18:17:23