public
class
containersingleton
/** * 容器:用來儲存物件
*/private
static map
ioc =
newconcurrenthashmap
();/**
* 獲取對應的bean
* @param classname
* @return
*/public
static object getbean
(string classname)
catch
(exception e)
return obj;
}return ioc.
get(classname);}
}
此方法執行緒不安全,會出現併發問題
public
static
void
main
(string[
] args)).
start();}}
結果:由於併發,出現了三個例項
/** * 容器:用來儲存物件
*/private
static map
ioc =
newconcurrenthashmap
();/**
* 獲取對應的bean
* @param classname
* @return
*/public
static object getbean
(string classname)
catch
(exception e)
return obj;
}return ioc.
get(classname);}
}}
單例模式六(註冊式單例)
概念 每個例項都快取到統一容器管理,通過唯一標識獲取對應的例項 也可稱為容器式單例 public class containersingletion private static hashmapioc new hashmap protected static object getinstance s...
單例(懶漢式單例 餓漢式單例)
public class singleton private static singleton instance new singleton public static singleton getinstance public class singleton public static synchr...
餓漢式單例和懶漢式單例
當我們想要乙個類只產生乙個例項化物件時,就需要用到單例模式,單例設計模式分為兩種 餓漢式和懶漢式。1 餓漢式單例 當用到這個類時,不管是否需要乙個物件都會建立乙個例項化物件 public class singleton public static singleton getinstance publ...