单例模式两种实现方法,优缺点各是什么?

实现一

//单例模式一
public class Test{
  private static Test test = new Test();
  public Test(){};
  public static Test getInstance(){
    return test;
  }
}
    优点:当类被加载的时候,已经创建好了一个静态的对象,因此,是线程安全的; 缺点:这个对象还没有被使用就被创建出来了。

实现二

//单例模式二
public class Test{
    private static Test test = null;
    private Test(){};
    public static Test getInstance(){
        if(test == null){
            test = new Test();
        }
        return test;
    }
}
    优点:按需加载对象,只有对象被使用的时候才会被创建 缺点:这种写法不是线程安全的,例如当第一个线程执行判断语句if(test = null)时, 第二个线程执行判断语句if(test = null),接着第一个线程执行语句test = new Test(), 第二个线程也执行语句test = new Test(),在这种多线程环境下,可能会创建出来两个对象。
经验分享 程序员 微信小程序 职场和发展