java-单例设计模式

1饿汉式

class Single //类一加载,对象就已经存在了。
 { 
 private static Single s = new Single();  
 private Single(){}  
 public static Single getInstance()  {   return s;  }
}


2懒汉式

class Single2  //类加载进来,没有对象,只有调用了getInstance方法时,才会创建对象。      //延迟加载形式。  { 
 private static Single2 s = null;  
 private Single2(){}  
 public static Single2 getInstance() 
 {   if(s==null)    s = new Single2();   return s;  } 
}

 

posted @ 2016-04-16 15:18  aipohoo  阅读(109)  评论(0编辑  收藏  举报