单例模式的实现方案:建立一个类,其构造方法都是私有的,只有一个getInstance()方法是public的,通过这个方法获取该类的唯一实例,即让类自身保存这个唯一的实例。
(1)懒汉式,线程不安全
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
(2)懒汉式,线程安全
最简单的方法就是将整个getInstance()方法设为同步(Synchronized)。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
(3)双重检验锁,线程安全
虽然(2)做到了线程安全,并且解决了多实例的问题&#