實(shí)現(xiàn)方式:
1. 餓漢模式
? 使用前創(chuàng)建一個(gè)單例,每次獲取同一個(gè)單例
? 通過static靜態(tài)代碼塊或靜態(tài)變量初始化
private static Instance instance=new Instance();
public static getInstance(){
? return instance;}
2. 懶漢模式
? 第一次使用時(shí)創(chuàng)建單例,后續(xù)使用獲取同一個(gè)單例
? ? 第一次創(chuàng)建時(shí)需要加同步鎖,避免多線程問題
? private static Instance instance=null;
public static getInstance(){
if(null==instance){
? ? synchronized(Object.class){
? ? ? ? ? instance=new Instance();
? ? }
? return instance;
}
3. 注冊(cè)模式
初始化時(shí)向map中注冊(cè)對(duì)象實(shí)例,在使用時(shí)從map中獲取
這種方式是Spring Ioc中獲取單例的方式。
4. 枚舉單例
枚舉中的對(duì)象都是單例的,常用于常量對(duì)象。
補(bǔ)充:序列化如何保證單例
在對(duì)象中增加public Object readResolve()方法,并返回單例。該方法由jvm調(diào)用,由該方法返回的對(duì)象替換在反序列化過程中創(chuàng)建的對(duì)象