手记

java单例模式四种实现方式

1.饿汉式

  public class DownLoad{

  private static final DownLoad mDownload =new DownLoad();

  private download(){

  }

  public static DownLoad getInstance(){

  return mDownload ;

  }

  }

2.懒汉式

 public class DownLoad{

  private static final DownLoad mDownload ;

  private download(){

  }

  public static DownLoad getInstance(){

    if(mDownload ==null){

    mDownload =new DownLoad();

    }

  return mDownload ;

  }

  }

3.double check(会出现空指针问题,可通过添加volatile关键字解决)

  public class DownLoad{

  private static volatile DownLoad mDownload ;

  private download(){

  }

  public static DownLoad getInstance(){

    if(mDownload ==null){

    synchronized(DownLoad.class){

      if(mDownload ){

        mDownload =new DownLoad();

      }

    }

   }

  return mDownload ;

  }

 }

4.静态内部类

  public class DownLoad{

    public static class{

    private static DownLoad mDownload=new DownLoad();

    public static DownLoad getInstance(){

      return mDownload;

    }

  }

}

原文链接:http://www.apkbus.com/blog-948824-77440.html

0人推荐
随时随地看视频
慕课网APP