单例模式实现的几种方式

来源:互联网 发布:剑网三秀太捏脸数据 编辑:程序博客网 时间:2024/05/29 03:47

饿汉式:

public class Singleton {    private static Singleton sInstance = new Singleton();    private Singleton() {};    public static Singleton getSinstance() {        return sInstance;    }}

饿汉式在类创建的时候就已经创建一个静态的对象,不论是否使用,它都一直存在,都会占用内存,相应的第一次调用时速度也快.而且,天生线程安全.
懒汉式:

public class Singleton {    private static Singleton sInstance = null;    private Singleton() {};    public synchronized static Singleton getsInstance() {        if (sInstance == null)            sInstance = new Singleton();        return sInstance;    }}

对比可以看到懒汉式只用在第一次调用时才会去创建对象,考虑到可能同时有多个地方去初始化对象,所以线程不安全,需要加synchronized关键字.第一次调用时会比饿汉式慢.
而且,每次调用getsInstance()都要去进行synchronized同步,性能上会差很多.所以就有了优化版的懒汉式写法,也叫做双重检查写法:

public class Singleton {    private static Singleton sInstance = null;    private Singleton() {};    public static Singleton getsInstance() {        if (sInstance == null) {            synchronized(Singleton.class) {                if (sInstance == null)                    sInstance = new Singleton();            }        }        return sInstance;    }}

这样的话只有在第一次初始化时进行synchronized同步,以后每次调用都只判断是否为null.推荐第一种和第三种写法,可根据需要进行选择.

原创粉丝点击