五、单件模式

经典单件

public class Singleton {
    private static Singleton uniqueInstance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

线程安全的单件

  • 直接生成单件对象
public class Singleton {
    private static Singleton uniqueInstance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return uniqueInstance;
    }
}
  • 使用synchronized
public class Singleton {
    private static Singleton uniqueInstance;
    private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}
  • 双重检查加锁
public class Singleton {
    private volatile static Singleton uniqueInstance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

个人理解

单件模式确保一个类只有一个实例,并提供一个全局访问点。
在经典的单件模式中,如果有两个线程访问一个单件模式,会发生线程安全的问题,产生两个单件实例。
解决方法:
1、在单件中直接生成单件对象,然后返回。(如果单件对象创建的开销比较大,会造成资源浪费)
2、在单件的全局访问点上使用synchronized 关键字,可以解决问题。(线程同步会降低性能)
3、使用双重检查加锁的方式,完美的解决问题。

原文地址:https://www.cnblogs.com/huacesun/p/6622496.html