//懒汉式 public class Singleton { private Singleton() {} private static Singleton SING = null; public static Singleton singsing(){ if(SING == null){ SING = new Singleton(); } return SING; } } //使用内部类实现线程安全的懒汉模式 public class Singleton { //内部类 private static class MySingletonHandler{ private static Singleton instance = new Singleton(); } private Singleton(){} public static Singleton getInstance(){ return MySingletonHandler.instance; } } //使用双重检测机制实现线程安全的懒汉式 public class Singleton{ private Singleton(){} private static volatile Singleton instance = null; public static Singleton getInstance() { if(instance == null){ synchronized (Singleton.class) { if(instance == null) instance = new Singleton(); } } return instance; } } //饿汉式 public class Singleton { private Singleton(){} private static final Singleton SING = new Singleton(); public static Singleton s(){ return SING; } }
30
2017
08
JAVA--单例模式
作者:MaoDehao | 分类:典型题 | 浏览:1107 | 评论:0
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。