Android/Java 单例模式

耳熟能详,这里我归纳为5种

1、饿汉式

/**
 * 饿汉式
 * 线程安全,instance在类装载时就实例化,在不需要考虑lazy load效果时可以使用
 */
public class Singleton1 {
    private static Singleton1 instance = new Singleton1();

    private Singleton1() {

    }

    public static Singleton1 getInstance() {
        return instance;
    }

    //饿汉式的另一种写法,成效跟上面的写法是一样的,都没有lazy load效果
//    private static Singleton1 instance = null;
//
//    static {
//        instance = new Singleton1();
//    }
//
//    private Singleton1() {
//
//    }
//
//    public static Singleton1 getInstance() {
//        return instance;
//    }

}

2、懒汉式

/**
 * 懒汉式
 * 这里细分的话,可以分为两种
 * 一种是最基础的,线程不安全,在单线程的时候可以使用
 * 另一种是线程安全的,但是效率低
 * 之所以写在一块,是因为这细分的两种写法都不推荐使用
 */
public class Singleton2 {

    private static Singleton2 instance = null;

    private Singleton2() {

    }

    /**
     * 线程不安全
     */
    public static Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }

    /**
     * 线程安全,但是效率低
     */
    public synchronized static Singleton2 getSafeInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}

3、双重检验锁

/**
 * 双重校验锁的方式 Double CheckLock(DCL)
 * 线程安全,从懒汉式演变而来,兼顾了安全和性能,推荐使用
 */
public class Singleton3 {
    //这里添加了 volatile 关键字,这是JDK1.5之后提供的对于volatile修饰的变量在读写操作时,不允许乱序
    public volatile static Singleton3 instance = null;

    private Singleton3() {

    }

    /**
     * 常见的写法
     */
    public static Singleton3 getInstance() {
        if (instance == null) {
            synchronized (Singleton3.class) {
                if (instance == null) {
                    instance = new Singleton3();
                }
            }
        }

        return instance;
    }

    /**
     * 这种写法能提升性能,原因跟使用了volatile有关,
     * 因为直接访问volatile开销比较大,所以减少访问次数自然可以减少开销
     */
    public static Singleton3 getInstanceBetter() {
        //定义临时变量
        Singleton3 tmp = instance;
        if (tmp == null) {
            synchronized (Singleton3.class) {
                tmp = instance;
                if (tmp == null) {
                    tmp = new Singleton3();
                    instance = tmp;
                }
            }
        }

        return tmp;
    }
}

4、静态内部类

/**
 * 静态内部类的方式
 * 线程安全,推荐使用
 */
public class Singleton4 {

    private static class SingletonHolder {
        private static final Singleton4 INSTANCE = new Singleton4();
    }

    private Singleton4() {

    }

    public static Singleton4 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

5、枚举

/**
 * 枚举的方式
 * 线程安全
 */
public enum Singleton5 {
    INSTANCE;
}

参考链接

单例模式的七种写法
Java 单例真的写对了么? 对双重检验锁的方式进行着重研究

你可能感兴趣的:(Android/Java 单例模式)