创建模式之单例模式
懒汉模式:
/** * @author yuyang * @DATE 2019/1/7 0007-8:59 */ public class Singleton { private final static Singleton INSTANCE=null; private Singleton(){} public static synchronized Singleton getInstance(){ if (INSTANCE==null){ return new Singleton(); }else { return INSTANCE; } } }
饿汉模式
public class Singleton { private final static Singleton INSTANCE = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return INSTANCE; } }
静态内部类
public class Singleton { private Singleton() {} private static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonInstance.INSTANCE; } }
同步方法
同步代码块
双重检查
public class Singleton { private static volatile Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }