Android 开发小经验

单例的写法

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

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

但是这种写法线程不安全,于是我们会加个锁,这样写

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

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

网上大部分都这样写 ,bingo 这样写完全没有问题,但是这样写效率比较低,
在Java1.5就引入了一个新的关键字—volatile,现在就有了双重检验校验的写法:

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

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

上面这种方法用的比较多,这里还有一种静态final的写法

public class Singleton {
    private Singleton() {}
    private static class SingletonLoader {
        private static final Singleton INSTANCE = new Singleton();
    };

    public static Singleton getInstance() {
        return SingletonLoader.SINGLETOP_INSTANCE;
    }
}

你可能感兴趣的:(android,开发,android,经验)