Java 單例設計模式

Singleton:單例模式安全

1.在整個應用程序中,一個類只有一個實例對象多線程

2.這個實例對象只能經過本類中建立=====>私有化構造測試

3.別人還得使用,經過本類中建立的一個對外訪問的接口,來返回本類的實例對象spa

實現單例的3種模式:線程

1.懶漢式:只有用戶第一次調用getInstence()的時候,對象的惟一實例纔會被調用對象

建立懶漢單例模式的步驟:接口

01.建立靜態變量get

private static Student stu;class

02.私有化構造變量

private Student(){}

03.提供對外訪問的接口

public static synchronized Student getInstence(){

if(stu==null){

stu=new Student();

}

return stu;

}

04.測試類中使用

Student.getInstence()

2.餓漢式:(推薦使用)在類加載的時候,單例對象就被建立,是線程安全的

建立餓漢單例模式的步驟:

01.建立靜態變量

private static Student stu=new Student();

02.私有化構造

private Student(){}

03.提供對外訪問的接口

public static synchronized Student getInstence(){

return stu;

}

04.測試類中使用

Student.getInstence()

3.雙重校驗鎖:爲了保證多線程狀況下,單例的正確性

建立雙重校驗鎖單例模式的步驟:

01.建立靜態變量

private static Student stu;

02.私有化構造

private Student(){}

03.提供對外訪問的接口

public static synchronized Student getInstence(){

if(stu==null){

synchronized(Student.class){

if(stu==null){

stu=new Student();

}

}

}

return stu;

}

04.測試類中使用

Student.getInstence()

相關文章
相關標籤/搜索