笔试Java实现单例设计模式(最优方案)
2017-08-15 22:20
477 查看
public class SingletonTest { private SingletonTest() //构造函数私有化 { } private static class Inner //私有的静态内部类 { static SingletonTest singletonTest = new SingletonTest(); } public static SingletonTest getInstance() { return Inner.singletonTest; } }
因为静态内部类只有在使用的时候才会被Classloader 加载。而JVM 类加载的时候又是线程安全的。
其他实现方法:
最常见(懒汉式)【线程不安全】:
public class SingletonTest { private static SingletonTest singletonTest = null; private SingletonTest() { } public static SingletonTest getInstance() { //在类的静态方法中实例化单例 if (null == singletonTest) { singletonTest = new SingletonTest(); } return singletonTest; } }
饿汉式
public class SingletonTest { //在类里面实例化静态成员变量 private static SingletonTest singletonTest = new SingletonTest(); private SingletonTest() { } public static SingletonTest getInstance() { return singletonTest; } }
双重检查锁
public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; }
双重检查锁定背后的理论是完美的。不幸地是,现实完全不同。双重检查锁定的问题是:并不能保证它会在单处理器或多处理器计算机上顺利运行。
相关文章推荐
- 23种经典设计模式的java实现_3_桥接模式
- AIX 程序设计大赛-AIX正方形问题算法及Java程序实现(方案三)
- 用Java实现的设计模式系列(3)--Builder
- 23种经典设计模式的java实现_4_生成器模式
- GoF设计模式学习之一:单例模式(Java实现)
- 23种经典设计模式的java实现_3_桥接模式
- 23种经典设计模式的java实现_1_抽象工厂模式
- 使用观察者模式实现Java应用程序设计MVC模式
- 23种经典设计模式的java实现_5_职责链模式
- 23种经典设计模式的java实现_5_职责链模式
- 怎样使用Java实现Factory设计模式
- observer设计模式的java实现
- 设计模式解析和实现(C++, java)之二十--状态(state)模式
- JAVA23种设计模式实现
- 23种经典设计模式的java实现_4_生成器模式
- observer设计模式的java实现
- 23种经典设计模式的java实现_2_适配器模式
- 用Java实现的设计模式-Factory
- 23种经典设计模式的java实现_2_适配器模式
- 用Java实现的设计模式系列(2)-Prototype