单例模式

/*
* 懒汉式单例模式(安全效率低)
*/

public class LazySingleton {

private static LazySingleton instance=null;

//私有构造器
private LazySingleton() {}

public static synchronized LazySingleton getInstance() {

if(instance==null) {
instance=new LazySingleton();
}

return instance;
}

}

/*
* 饿汉式单例模式(不安全,效率高)
*/
public class EagerSingleton {

//私有构造器
private EagerSingleton() {}

private static EagerSingleton instance=new EagerSingleton();

public static EagerSingleton getInstance() {

return instance;

}

}

/*
* 双重检查加锁
* 所谓双重加锁机制,指的是:并不是每次进入getInstance方法都需要同步,而是先不同步,进入方法后,
* 先检查实例是否存在,如果不存在才进行下面的同步块,这是第一重检查,进入同步块过后,再次检查实例是否
* 存在,如果不存在,就在同步的情况下创建一个实例,这是第二次检查。这样以来,只需要同步一次了,进而提高
* 了效率。
*/

public class SynthesizeSinleton {

private volatile static SynthesizeSinleton instance=null;

private SynthesizeSinleton() {}

public static SynthesizeSinleton getInstance() {

//先检查实例是否存在,如果不存在才进行下面语句
if(instance==null) {

//同步块,线程安全的创建实例
synchronized (SynthesizeSinleton.class) {

//第二次实例是否存在,如果不存在才真正的创建实例
if(instance==null) {

instance =new SynthesizeSinleton();
}
}
}

return instance;

}
}

原文地址:https://www.cnblogs.com/sort/p/8324799.html