【设计模式之单例模式InJava】

时间:2023-03-09 13:39:29
【设计模式之单例模式InJava】

1. 单例模式

  1.1饿汉式(开发常用)

class SingleFirst
{
  /*
   添加其他成员信息
  */
  private static SingleFirst s1 = new SingleFirst();
  private SingleFirst(){
  }
  public static SingleFirst getInstance(){
    return s1;
  }
}

  1.2 懒汉式  

    

class SingleSecond
{
  /*
   添加其他成员信息
  */
  private static SingleSecond s2 = null;
  private SingleSecond(){
  }
  public static SingleSecond getInstance(){
    if(null==s2)
     s2 = new SingleSecond();
    return s2;
  }
}