- 单例实现1:经典单例模式(Classic singleton pattern)
- 实现延迟实例化(Lazy instantiaze);线程不安全(thread-unsafe)
- 可用来学习单例模式思想,但是因为线程不安全,所以不建议使用。
- /**
- * Classic singleton pattern
- * @author <a href="mailto:ifuteng@gmail.com">futeng</a>
- */
- public class Singleton {
- // private static variable
- private static Singleton singleton;
- // private constructor
- private Singleton() {
- // do something useful such as initialized data
- }
- // provides a global point of access to it
- public static Singleton getInstance() {
- if ( singleton == null) {
- singleton = new Singleton();
- }
- return singleton;
- }
- }
- 单例实现2:对方法同步加锁式单例(Synchronized method singleton pattern)
- 实现延迟实例化(Lazy instantiaze);线程安全(thread safe);每次访问都要等候别的线程离开该方法,性能低。
- 解决了经典单例模式线程不安全的问题,但是性能低下,所以不建议使用。
- /**
- * Synchronized method singleton pattern
- * @author <a href="mailto:ifuteng@gmail.com">futeng</a>
- */
- public class Singleton {
- private static Singleton singleton;
- private Singleton() {}
- public static synchronized Singleton getInstance() {
- if ( singleton == null) {
- singleton = new Singleton();
- }
- return singleton;
- }
- }
- 单例实现3:无延迟实例化式单例(Eagerly instantiaze singleton pattern)
- 非延迟实例化(eagerly instantiaze);线程安全(thread safe);
- 在类加载的第一时间被初始化,大部分场景都可胜任。丢失了延迟实例化特性,这带来的遗憾是还未被调用就已经实例化了。
- /**
- * Eagerly singleton pattern
- * @author <a href="mailto:ifuteng@gmail.com">futeng</a>
- */
- public class Singleton {
- private static Singleton singleton = new Singleton();
- private Singleton() {}
- public static synchronized Singleton getInstance() {
- return singleton;
- }
- }
- 单例实现4:双重检测加锁式单例(Double-checked locking singleton pattern)
- 实现延迟实例化(Lazy instantiaze);线程安全(thread safe);
- 在最佳的单例实现,稍微复杂。
- /**
- * Double checked singleton pattern
- * @author <a href="mailto:ifuteng@gmail.com">futeng</a>
- */
- public class Singleton {
- private volatile static Singleton singleton = new Singleton();
- private Singleton() {}
- public static Singleton getInstance() {
- if ( singleton == null) {
- synchronized (Singleton. class) {
- if ( singleton == null) {
- singleton = new Singleton();
- }
- }
- }
- return singleton;
- }
- }