懶漢模式與餓漢模式

2021-08-27 04:32:33 字數 499 閱讀 4189

懶漢模式:加截類的時候就建立物件

class single

private static single s = new single();

pubic static single getinstance()

}

餓漢模式:呼叫getinstance()方法時才建立物件

class single

private static single s = null;

public static single getinstance()} }

}}

從上面可以看出,懶漢模式雖然實現了延遲載入,但會導致執行緒同步的問題。為了實現同步,不得不加同步鎖。

如果直接在方法上加synchronized鎖,每次呼叫時都要判斷鎖,效率比較低。所以採用上面**的方法實現同

步。但這樣使**繁瑣了不少,所以通常情況下還是用餓漢模式建立單例。

餓漢模式和懶漢模式

package pattern.singleton 餓漢式單例類.在類初始化時,已經自行例項化 public class singleton1 已經自行例項化 private static final singleton1 single new singleton1 靜態工廠方法 public st...

餓漢模式vs懶漢模式

餓漢式 建立物件例項的時候直接初始化 空間換時間 public class singletonone 2 建立該型別的私有靜態例項 private static singletonone instance newsingletonone 3 建立公有靜態方法返回靜態例項物件 public stati...

懶漢模式和餓漢模式

1.懶漢模式 在類載入的時候不被初始化,懶漢模式是延遲載入,在需要的時候才建立物件。public class jdbcutil public static jdbcutil getinstance return jdbcutil 2.餓漢模式 在類載入的時候完成了初始化,但是載入比較慢,獲取物件比較...