单例模式

来源:互联网 发布:南宁java培训 编辑:程序博客网 时间:2024/06/11 22:22

 饿汉式单例类
public class EagerSingleton{
    private static final EagerSingleton m_instance=new EagerSingleton();
    /**
     私有的默认构造子
   **/
  private EagerSingleton(){}


  public static EagerSingleton getInstance(){
         return m_instance;

   }
}

懒汉式单例类
public class LazySingleton{
   private static LazySingleton l_instance=null;
  
   private LazySingleton(){}


  synchronized public static LazySingleton getInstance(){
      if(l_instance==null){

        l_instance=new LazySingleton();
      }
     return l_insatnce;


}
  

}