單例模式是我們經常用的設計模式之一,下面記一下幾種常用的單例模式的寫法,方便自己查閱
1.餓漢單例模式--缺點就是不能延遲載入
class singltondemoone
public static singltondemoone getsingltondemoone()
}
2.懶漢單例模式--懶載入
class singltondemotwo
public static singltondemotwo getsingltondemotwo()
return singltondemotwo;
}}
上面的雖然實現了懶載入,但並不適用語多執行緒下,修改加上syncihronized
class singltondemotwo
public static singltondemotwo getsingltondemotwo()}}
return singltondemotwo;
}}
3.使用靜態內部類
class singletondemothree
private singletondemothree ()
public singletondemothree getsingleton()
}
java的幾種單例模式
1 賴漢式 public class lazysingleton public static lazysingleton getinstance 2 餓漢式 public class hungrysingleton public static hungrysingleton getinstance ...
java中幾種單例寫法
方法一 餓漢式 優點 執行緒安全 缺點 效率低。public class singleton 加static和final private static final singleton instance new singleton public static singleton getinstance...
單例(懶漢式單例 餓漢式單例)
public class singleton private static singleton instance new singleton public static singleton getinstance public class singleton public static synchr...