本篇涉及語言java kotlin c++
概念最簡單的一個設計模式,但是實現起來還是有很多需要注意的地方。而且也是被常被不合時宜使用的設計模式,下面會先看一下使用場景,再去展開說明實現方式
一、單例和靜態類
意圖:保證一個類僅有一個實例,并提供一個訪問它的全局訪問點。
主要解決:一個全局使用的類頻繁地創建與銷毀。
何時使用:當您想控制實例數目,節省系統資源的時候。
如何解決:判斷系統是否已經有這個單例,如果有則返回,如果沒有則創建。
關鍵代碼:構造函數是私有的。
靜態類也有相似的功能,下面比較一下兩者區別。
名稱 | 優點 | 缺點 | 適用場景 |
---|---|---|---|
單例 | 可以繼承,實現接口,覆寫,懶加載 | 內存難被清理回收 | 必須有且只有一個對象的場景(例如:log系統,線程池) |
靜態類 | 產生對象會隨靜態方法執行完而被釋放 | 沒有面向對象特性 | 工具類 |
二、單例的實現方式
java
1.餓漢模式(線程安全)
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2.懶漢模式
(1)非線程安全實現
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
(2)線程安全實現
雙檢鎖/雙重校驗鎖
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
(3)登記式/靜態內部類(線程安全)
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
(4)枚舉(線程安全)
public enum Singleton6 {
INSTANCE;
public void whateverMethod() {}
}
(5)使用ThreadLocal(線程安全)
public class Singleton {
private static final ThreadLocal<Singleton> tlSingleton = new ThreadLocal<Singleton>() {
@Override
protected Singleton initialValue() {
return new Singleton();
}
};
private Singleton() {}
public static Singleton getInstance() {
return tlSingleton.get();
}
}
(6)使用CAS鎖(線程安全)
public class Singleton {
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();
private Singleton() {
}
public static Singleton getInstance() {
for (; ; ) {
Singleton current = INSTANCE.get();
if (current != null) {
return current;
}
current = new Singleton();
if (INSTANCE.compareAndSet(null, current)) {
return current;
}
}
}
}
名稱 | 是否懶加載 | 是否線程安全 | 優點 | 缺點 | 適用場景 |
---|---|---|---|---|---|
懶漢式線程不安全 | 是 | 否 | 實現簡單 | 非線程安全 | 不建議使用 |
懶漢式線程安全 | 是 | 是 | 實現簡單;第一次調用才初始化,避免內存浪費 | 加鎖會影響效率 | 不建議使用 |
餓漢式 | 否 | 是 | 實現簡單;沒有加鎖,執行效率高 | 類加載時就初始化,浪費內存 | 默認情況下推薦使用(沒有懶加載需求,也不考慮反序列化) |
登記式/靜態內部類 | 是 | 是 | 兼顧運行效率和懶加載需求 | / | 有懶加載需求情況下,默認使用方案 |
枚舉 | 是 | 是 | 實現簡單(面試的時候寫代碼可以快人一步,哈哈); 自動支持序列化機制 | 不能用反射調用私有構造函數 | Effective Java 作者 Josh Bloch 提倡的方式,感覺面試用的更多一些 |
使用ThreadLocal | 是 | 是 | 多了解一個知識點,ThreadLocal會為每一個線程提供一個獨立的變量副本,從而隔離了多個線程對數據的訪問沖突。 | 實現復雜 | 面試 |
使用CAS鎖 | 是 | 是 | 多了解一個知識點 | 實現復雜 | 面試 |
kotlin
(1)object關鍵字的餓漢模式
object Singleton{}
用as轉成字節碼再反編譯后的java代碼,可以看出是餓漢模式
public final class Singleton{
public static final Singleton INSTANCE;
private Singleton(){}
static {
Singletonvar0 = new Singleton();
INSTANCE = var0;
}
}
除了object實現餓漢模式之外,其他和java形式雷同。
C++
c++除了私有構造函數,還要注意賦值拷貝接口,內存安全的問題
- 全局只有一個實例:static 特性,同時禁止用戶自己聲明并定義實例(把構造函數設為 private)
- 線程安全
- 禁止賦值和拷貝(操作符重載)
- 用戶通過接口獲取實例:使用 static 類成員函數()
(1)線程安全,內存安全的懶漢模式(智能指針,鎖)
#include <iostream>
#include <memory> // shared_ptr
#include <mutex> // mutex
// version 2:
// with problems below fixed:
// 1. thread is safe now
// 2. memory doesn't leak
class Singleton{
public:
typedef std::shared_ptr<Singleton> Ptr;
~Singleton(){
std::cout<<"destructor called!"<<std::endl;
}
Singleton(Singleton&)=delete;
Singleton& operator=(const Singleton&)=delete;
static Ptr get_instance(){
// "double checked lock"
if(m_instance_ptr==nullptr){
//只有判斷指針為空的時候才加
//避免每次調用 get_instance的方法都加鎖
//鎖的開銷畢竟還是有點大的
std::lock_guard<std::mutex> lk(m_mutex);
if(m_instance_ptr == nullptr){
m_instance_ptr = std::shared_ptr<Singleton>(new Singleton);
//m_instance_ptr析構時,new出的對象也會被delete掉
}
}
return m_instance_ptr;
}
private:
Singleton(){
std::cout<<"constructor called!"<<std::endl;
}
static Ptr m_instance_ptr;
static std::mutex m_mutex;
//Singleton(const A&); //拷貝構造函數,C++11之前delete的替代方案
//Singleton& operator=(const A&);//拷貝復制運算符,C++11之前delete的替代方案
};
// initialization static variables out of class
Singleton::Ptr Singleton::m_instance_ptr = nullptr;
std::mutex Singleton::m_mutex;
int main(){
Singleton::Ptr instance = Singleton::get_instance();
Singleton::Ptr instance2 = Singleton::get_instance();
return 0;
}
(2)局部靜態變量 懶漢式模式(推薦方式)
#include <iostream>
class Singleton
{
public:
~Singleton(){
std::cout<<"destructor called!"<<std::endl;
}
Singleton(const Singleton&)=delete;
Singleton& operator=(const Singleton&)=delete;
static Singleton& get_instance(){
static Singleton instance;
return instance;
}
private:
Singleton(){
std::cout<<"constructor called!"<<std::endl;
}
};
int main(int argc, char *argv[])
{
Singleton& instance_1 = Singleton::get_instance();
Singleton& instance_2 = Singleton::get_instance();
return 0;
}
這種方法又叫做 Meyers' SingletonMeyer's的單例, 是著名的寫出《Effective C++》系列書籍的作者 Meyers 提出的。所用到的特性是在C++11標準中的Magic Static特性:
- 通過局部靜態變量的特性保證了線程安全 (C++11, GCC > 4.3, VS2015支持該特性);
- 不需要使用共享指針,代碼簡潔;
- 注意在使用的時候需要聲明單例的引用 Single& 才能獲取對象。
(3)c++ call_once
在C++11中提供一種方法,使得函數可以線程安全的只調用一次。即使用std::call_once和std::once_flag。std::call_once是一種lazy load的很簡單易用的機制。實現代碼如下:
#include <iostream>
#include <memory> // shared_ptr
#include <mutex> // mutex
class Singleton
{
public:
~Singleton(){
std::cout<<"destructor called!"<<std::endl;
}
Singleton(const Singleton&)=delete;
Singleton& operator=(const Singleton&)=delete;
static Singleton& get_instance(){
static std::once_flag s_flag;
std::call_once(s_flag,[&](){
instance_.reset(new Singleton);
});
return *instance_;
}
private:
Singleton(){
std::cout<<"constructor called!"<<std::endl;
}
};
int main(int argc, char *argv[])
{
Singleton& instance_1 = Singleton::get_instance();
Singleton& instance_2 = Singleton::get_instance();
return 0;
}