如何正确实现一个单例设计模式

设计模式中的单例,是最常用,也算是比较简单的一个了。我们都知道,要想保证只有一个实例,通常采用加锁和双重检查的方式来实现单例,代码如下。

public class SingletonTest {
    private SingletonTest(){

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

}

这种写法的要点主要有如下几个,1,私有构造函数,即不允许直接调用构造函数new一个对象。2,静态实例。3,静态获取示例的方法。首先判断instance是否为null,然后加锁,然后再判断instance是否为null,之后进行初始化。最后返回示例。

做到这些就足够了吗?并不是。

我们都知道,jvm的内存模型,jvm中的线程有自己的工作内存,jvm有主内存,工作内存是主内存的拷贝,工作内存和主内存直接并不是实时一致的。一个线程创建了单例对象后,别的线程并不一定可以立刻感知到。所以,以上代码中,instance还需要用volatile来修饰,才能真正做到单例模式。修改后的代码如下。

public class SingletonTest {
    private SingletonTest(){

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

}

猜你喜欢

转载自blog.csdn.net/li_canhui/article/details/85088690
今日推荐