DCL 单例模式

137 阅读2分钟
单例模式:确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

1.饿汉式(静态常量)

  • 优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
  • 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
public class SingleTest {
    //私有化静态变量,直接new好对象
    private final static SingleTest INSTANCE = new SingleTest();
    
    //私有化构造方法
    private SingleTest(){}

    //公有get方法
    public static SingleTest getInstance(){
        return INSTANCE;
    }
}

2.懒汉式(线程不安全)

这种写法起到了Lazy Loading的效果,但是只能在单线程下使用。如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。

public class SingleTest {
    private  static SingleTest instance;

    private SingleTest(){}

    public static SingleTest getInstance(){
        if (instance == null){
            instance = new SingleTest();
        }
        return instance;
    }
}

//懒汉式 加锁 解决上面第三种实现方式的线程不安全问题
public class SingleTest {
    private  static SingleTest instance;

    private SingleTest(){}

    public static SingleTest getInstance(){
        synchronized (SingleTest.class){
            if (instance == null){
                instance = new SingleTest();
            }
        }
        return instance;
    }
}

DCL:Double Checked Locking (双重检查锁定)

public class SingleTest {
    //提供私有的静态属性(存储对象的地址)
    //加入volatile防止其他线程可能访问一个为null的对象
    private volatile static SingleTest instance;

    //构造器私有化(避免外部new构造器)
    private SingleTest(){}

    public static SingleTest getInstance(){
        //如果已经有对象,防止再次创建
        if (instance != null){
            return instance;
        }

        //有两个线程A B,A进来发现无对象,创建对象
        //此时B也进来,发现无对象,也创建对象,这样就有两个对象
        synchronized (SingleTest.class){
            if (instance == null){
                instance = new SingleTest();
            }
        }
        return instance;
    }
}