懶漢式(執行緒不安全)
餓漢式(執行緒安全,但是不能實現懶載入的效果)//懶漢式(執行緒不安全)
public
class
singleton
private
static singleton getinstance()
return singleton;}}
//改進一下,懶漢式(執行緒安全)
public
class
singleton
private
static
synchronized singleton getinstance()
return singleton;
}}
雙重校驗鎖(執行緒安全,有一定的效能損失)//餓漢式(但是沒有懶載入效果)
public
class
singleton
public
static singleton getinstance()
}
靜態內部類(執行緒安全,並且能夠實現懶載入效果)//雙重檢查模式(有一定的效能損失)
public
class
singleton
public
static singleton getinstance()
}}return singleton;
}}
//靜態內部類(推薦)
public
class
singleton
public
static singleton getinstance()
private
static
class
innerclass
}
單例模式 四種
餓漢式 單例模式 餓漢式類載入到記憶體後,例項化乙個單例,jvm保證執行緒安全 都不能建立新的,所以安全,多執行緒都是安全的 簡單易用 缺點 不管是否用到,類載入時候就會例項化,浪費 一般專案開發中載入是用的class.forname 將class載入到記憶體,但不例項化,此時,如果使用餓漢,就會消...
四種單例設計模式
public class singletonlazy 私有化該類的構造器 public static singletonlazy getinstance 如果沒有例項,就建立乙個 return instance 返回例項物件 public class singletonhungary 私有化該類的構...
python四種實現單例模式
coding utf 8 author xianyt date 2018 func 在預設的情況下建立多個物件的id不相同,如果想要設定為單例模式,可以通過 new 方法中的 instance 在 new 方法中把類例項繫結到類變數 instance上,如果cls.instance為none表示該類...