java基础-单例设计模式

//类加载时,对象已经创建

class Single{

  private static  Single s = new Single();

  private Single(){}

  public static Single getInstance(){

    return  s;

  }

}

 

//类加载时,未创建对象,在调用 getInstance方法时,才会创建对象

//延迟类的加载

class Single{

  private static Single s = null;

  private Single(){}

  public static Single getInstance(){

    if(s==null){

      s=new Single();

    }

    return s;

  }

}

 

 //考虑线程,以及优化 延迟加载类型

class Single{

  private static Single s = null;

  private Single(){}

  public static Single getInstance(){

   if(s==null){  //加判断,解决效率问题:避免产生对象后,每次判断锁,影响程序效率

     synchronized(Single.class){  //加锁,解决线程安全问题

       if(s==null){

          s=new Single();

         }

      }

  }

    return s;

  }

}

 

posted on 2014-04-17 17:50  梵阿林  阅读(89)  评论(0)    收藏  举报

导航