多种单例模式
//1 懒汉,线程不安全 public class Singleton { private static Singleton instance = null; private Singleton(){} public static Singleton getInstance(){ if(instance == null ) { instance = new Singleton(); } return instance; } } //2 懒汉,线程安全 public class Singleton { private static Singleton instance = null; private Singleton(){} public static synchronized Singleton getInstance(){ if(instance == null ) { instance = new Singleton(); } return instance; } } //3 饿汉 public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } } //4 静态内部类 public class Singleton { private static class SingletonHolder { public static Singleton instance = new Singleton(); } private Singleton(){} public static Singleton getInstance(){ return Singleton.SingletonHolder.instance; } } //5 枚举 public class Singleton { private Singleton(){} public static Singleton getInstance(){ return Single.instance.getInstance(); } private static enum Single { instance; private Singleton single; //JVM会保证此方法绝对只调用一次 private Single(){ single = new Singleton(); } public Singleton getInstance(){ return single; } } } //6 双重校验锁 public class Singleton { private static volatile Singleton instance = null; private Singleton(){} private static Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { if(instance == null){ instance = new Singleton(); } } } return instance; } }
相关推荐
gongruitao 2020-05-02
xiaoemo0 2020-04-08
ahnuzfm 2020-02-03
Ingram 2020-01-16
fraternityjava 2020-06-14
Kele0 2020-05-30
ahnuzfm 2020-05-07
elizabethxxy 2020-04-27
付春杰Blog 2020-03-26
JF0 2020-03-20
缘起宇轩阁 2019-12-30
gongruitao 2020-01-04
zuixin 2020-01-03
pengkunstone 2019-12-27