懶漢模式和餓漢模式

2022-08-28 17:42:11 字數 688 閱讀 8285

1.懶漢模式

在類載入的時候不被初始化,懶漢模式是延遲載入,在需要的時候才建立物件。

public

class

jdbcutil

public

static

jdbcutil getinstance()

return

jdbcutil;

}}

2.餓漢模式

在類載入的時候完成了初始化,但是載入比較慢,獲取物件比較快,類建立的同時就已經建立好了乙個靜態的物件供系統使用。

public

class

jdbcutil

public

static

jdbcutil getinstance()

}

3.餓漢模式和懶漢模式的區別

餓漢模式由於在類建立的同時就建立了靜態物件供系統使用,所以執行緒是安全的。

懶漢模式由於延時載入,是在需要的時候才建立物件並且如果不加上synchronized會導致物件的訪問不是執行緒安全的。

餓漢模式和懶漢模式

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

懶漢和餓漢模式

單例就是該類只能返回乙個例項。單例所具備的特點 1.私有化的建構函式 2.私有的靜態的全域性變數 3.公有的靜態的方法 單例分為懶漢式 餓漢式和雙層鎖式 單例分為懶漢式 餓漢式和雙層鎖式 餓漢式 public class singleton1 private static singleton1 si...

懶漢模式與餓漢模式

懶漢模式 加截類的時候就建立物件 class single private static single s new single pubic static single getinstance 餓漢模式 呼叫getinstance 方法時才建立物件 class single private stat...