第七周作业

单例模式的两种实现方式:

单例模式:为了使一个类只能实例化一个对象,无论进行多少次实例化,其引用都指向一个对象。

第一种方式:

class Single
{
   private Single(){}
   private static Single s = new Single();
   public static Single getInstanse()
  {
         return s:
  }//提供到一个方法可以访问到该对象

}

该种方式优点:线程安全。

第二种方式:

class Single
{
  private static Single s = null;
  private Single(){};
  public static Single getInstance()
  {
    if(s==null)
    s = new Single();
    return s;
  }
}

该种方式在多线线程中需要同步。

posted @ 2016-04-16 21:13  酥猩猩  阅读(154)  评论(0编辑  收藏  举报