首页 > 代码库 > 多种单例模式
多种单例模式
//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; } }
多种单例模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。