单例模式
懒汉式(线程不安全)
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
懒汉式(线程安全) 加关键字synchronized
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
饿汉式(线程安全)
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
双检锁(安全且在多线程情况下能保持高性能)
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
其他枚举、内部类
-----------------------------------------------
*使用private修饰是避免外界直接通过类直接访问变量赋值
*使用static是为了被类的getInstance调用,同时类在初始化时只会初始化一次静态变量