設計模式

設計模式(一)


單例設計模式

單例就是某個實體只產生一個對象,如果只能產生一個對象那么就需要將構造函數設置為private的,那么就無法手動去創建該類的實體對象。

public class Student {

? ? ?private Student(){}

? ? ?private static Student s=new Student();

? ? ?public static Student getInstance(){

? ? ? ? ? return s;

? ? ?}

}

由于在類中直接創建除了實體的對象,這種方式被稱為餓漢式。但是如果創建該對象的時候需要消耗大量的資源,那么在不使用該對象的時候盡量不要去初始化

public class Student {

? ? ?private Student(){

? ? ?//消耗很多資源

? ? ?}

? ? ?private static Student s;

? ? ?public static Student getInstance(){

? ? ? ? ? if(s==null){

? ? ? ? ? ? ? ?s=new Student();

? ? ? ? ? }

? ? ? ? ? return s;

? ? ?}

}

上面這種方式避免了在不需要使用實體對象的時候對實體對象進行初始化,但是在多線程并發的時候,會出現線程1執行到s=new Student()的時候線程2執行到if(s==null),這個時候就有可能創建兩個實體對象,為了避免以上的情況出現需要添加synchronized關鍵字。

public class Student {

? ? ?private static Student s;

? ? ?private Student(){}

? ? ?public static Student getInstance(){

? ? ? ? ? if(s == null){

? ? ? ? ? ? ? ?synchronized(Student.class){

? ? ? ? ? ? ? ? ? ? if(s == null){

? ? ? ? ? ? ? ? ? ? ? ? ?s = new Student();

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ?}

? ? ? ? ? }

? ? ? ? ? return instance;

? ? ?}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 前言 本文主要參考 那些年,我們一起寫過的“單例模式”。 何為單例模式? 顧名思義,單例模式就是保證一個類僅有一個...
    tandeneck閱讀 2,540評論 1 8
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,838評論 0 11
  • 面向對象的六大原則 單一職責原則 所謂職責是指類變化的原因。如果一個類有多于一個的動機被改變,那么這個類就具有多于...
    JxMY閱讀 975評論 1 3