單例模式六(註冊式單例)

2021-10-03 12:43:40 字數 1004 閱讀 6595

概念:每個例項都快取到統一容器管理,通過唯一標識獲取對應的例項 。也可稱為容器式單例

public class containersingletion 

private static hashmapioc = new hashmap();

protected static object getinstance(string name) catch (exception e)

ioc.put(name , instance);

return instance ;

} else

}}

新建測試類驗證

public class test 

}

public class exectorthread implements runnable 

}

通過如下測試

thread t1 = new thread(new exectorthread());

thread t2 = new thread(new exectorthread());

t1.start();

t2.start();

就發現會例項兩個不同物件。所以為了保證執行緒的安全性,還有需要改進,這裡可以採用雙重檢查鎖的方式

public class containersingletion 

private volatile static hashmapioc = new hashmap();

protected static object getinstance(string name) catch (exception e)

ioc.put(name , instance);

return instance ;

} else }}

return ioc.get(name);

}}

單例模式 懶漢式單例模式

單例模式有餓漢時模式和懶漢式 單例模式也就是說同一類只返回乙個物件供外部類使用 懶漢式即延遲初始化單例。在多執行緒環境下,簡單的懶漢式會有執行緒安全。懶漢式單例模式解決線性安全問題如下 1 使用雙重檢查鎖機制解決執行緒安全問題。2 單例模式還有更好的解決方案,即使用靜態類方式。懶漢式單例模式典型 p...

設計模式 單例模式 餓漢式單例和懶漢式單例

單例模式 singleton pattern 乙個在設計模式中比較簡單的模式,我們常說的餓漢式和懶漢式是最常舉例的兩種寫法。如下餓漢式 public class singleton 獲取例項物件 public static singleton getsingleton 懶漢式 public clas...

單例(懶漢式單例 餓漢式單例)

public class singleton private static singleton instance new singleton public static singleton getinstance public class singleton public static synchr...