设计模式————单例模式

单例模式

确保一个类只有一个实例,并提供一个全局访问点。

饿汉式,线程安全。场景:应用程序总是创建并使用单例实例,或者在创建和运行时方面的负担不太繁重。

public class Singleton {
    private static Singleton mInstance = new Singleton3();
    private Singleton3() {}

    public static Singleton3 getInstance() {
        return  mInstance;
    }
}

懒汉式,同步方法。场景:getInstance()(的性能对应用程序不是很关键。

public class Singleton {
    private static Singleton mInstance;
    private Singleton() {}

    public synchronized static Singleton getInstance() {
        if( mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }
}

双重检查加锁,减少getInstance()的时间耗费。

public class Singleton {
    private volatile static Singleton mInstance;
    private Singleton() {}

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

猜你喜欢

转载自www.cnblogs.com/kyun/p/10243669.html