Java 单例设计模式
Singleton:單例模式
1.在整個應用程序中,一個類只有一個實例對象
2.這個實例對象只能通過本類中創建=====>私有化構造
3.別人還得使用,通過本類中創建的一個對外訪問的接口,來返回本類的實例對象
實現單例的3種模式:
1.懶漢式:只有用戶第一次調用getInstence()的時候,對象的唯一實例才會被調用
創建懶漢單例模式的步驟:
01.創建靜態變量
private static Student stu;
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()
?
?
轉載于:https://www.cnblogs.com/s10-/p/8287252.html
總結
以上是生活随笔為你收集整理的Java 单例设计模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目第二周冲刺第六天
- 下一篇: badboy 2.2.5 安装包