98. 驗證二叉搜尋樹-中序遍歷-中等難度
阿新 • • 發佈:2020-07-14
顧名思義,單例模式就是要求只有一個實體物件。
單例模式分為懶漢式和餓漢式
餓漢式:一開始就建立物件,執行緒安全,但是如果用不到這個物件,會造成浪費
懶漢式:要的時候才建立,不會造成浪費,但是會有執行緒安全的問題.
餓漢式和懶漢式都是私有化建構函式,不讓外面能夠直接new 物件.
餓漢式
private static Hungry instance = new Hungry(); private Hungry(){} public Hungry getInstance(){ return instance; }
懶漢不安全式
public classLazyUnSafe { private LazyUnSafe instance; public LazyUnSafe getInstance(){ if(instance == null){ instance = new LazyUnSafe(); } return instance; } }
懶漢安全式
public class LazySafe { private LazySafe instance; private LazySafe(){} publicLazySafe getInstance() { if(instance == null){ synchronized (LazySafe.class){ if(instance == null){ instance = new LazySafe(); } return instance; } } return instance; } }