单例设计模式

单例模式

确保单例类只有一个实例,而且这个单例类提供一个借口让其他类获取到这个唯一的实例;

  • 如果某各类创建时,需要消耗太多的资源,或者这个类占用很多内存,如果创建太多这个类的实例会导致内存占用太多,此时我们就可以使用单例模式;

单例模式(懒汉写法,单线程)

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

考虑到线程安全的写法

public class Singleton {
    private static volatile Singleton instance = null;
    private Singleton(){
    }
    public static Singleton getInstance(){
        if (instance == null){
            synchronized ( Singleton.class){
                if (instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  • 第一次判断是为了避免不必要的同步,第二次判断是为了确保在此之前没有其他线程进入到sychronized块创建了新实例;
  • 不在public static Singleton getInstance()中加synchronized是为了避免同步执行,导致的效率低;
  • 由于instance = new Singleton();会执行1)给Singleton的实例分配内存,2)调用Singleton的构造函数初始化字段,3)将instance对象执行分配的对象,但是由于无法确保上面三个执行的顺序,有可能先将instance指向内存实例,再进行初始化,所有我们需要加上volatile修饰,线程每次调用volatile修饰的变量的时,都会去堆中拿最新的数据,确保instance是最新的。
    Android中的单例模式,比如:获取WindowManager对象的引用。

待续

GitHub:https://github.com/godfunc
博客园:http://www.cnblogs.com/godfunc
Copyright ©2019 Godfunc
原文地址:https://www.cnblogs.com/Godfunc/p/6554100.html