(1)懒汉式
优点:在需要的时候才去加载
缺点:在多线程的环境下,会出现线性不安全的情况
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
(2)饿汉式
优点:饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
(3)加双重锁
优点:在并发量不高、安全性不高的情况下可以很好的运行
缺点:在不同的编译环境下可能出现不同的问题
publci static synchronized Singleton getInstance(){
if(instance == null){
synchronized(Object){
if(instance == null){
instance = new Singleton();
}
}
}
}
(3)内部类
优点:延迟加载、线性安全、减少内存消耗
public class Singleton {
/**
* 私有的构造器
*/
private Singleton() {
}
/**
* 内部类实现单例模式
* 延迟加载,减少内存开销
*
*/
private static class SingletonInner {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonInner.instance;
}
}