本篇涉及語言java kotlin c++
概念最簡單的一個設(shè)計模式,但是實現(xiàn)起來還是有很多需要注意的地方。而且也是被常被不合時宜使用的設(shè)計模式,下面會先看一下使用場景,再去展開說明實現(xiàn)方式
一、單例和靜態(tài)類
意圖:保證一個類僅有一個實例,并提供一個訪問它的全局訪問點。
主要解決:一個全局使用的類頻繁地創(chuàng)建與銷毀。
何時使用:當(dāng)您想控制實例數(shù)目,節(jié)省系統(tǒng)資源的時候。
如何解決:判斷系統(tǒng)是否已經(jīng)有這個單例,如果有則返回,如果沒有則創(chuàng)建。
關(guān)鍵代碼:構(gòu)造函數(shù)是私有的。
靜態(tài)類也有相似的功能,下面比較一下兩者區(qū)別。
名稱 | 優(yōu)點 | 缺點 | 適用場景 |
---|---|---|---|
單例 | 可以繼承,實現(xiàn)接口,覆寫,懶加載 | 內(nèi)存難被清理回收 | 必須有且只有一個對象的場景(例如:log系統(tǒng),線程池) |
靜態(tài)類 | 產(chǎn)生對象會隨靜態(tài)方法執(zhí)行完而被釋放 | 沒有面向?qū)ο筇匦?/td> | 工具類 |
二、單例的實現(xiàn)方式
java
1.餓漢模式(線程安全)
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2.懶漢模式
(1)非線程安全實現(xiàn)
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
(2)線程安全實現(xiàn)
雙檢鎖/雙重校驗鎖
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)登記式/靜態(tài)內(nèi)部類(線程安全)
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;
}
}
}
}
名稱 | 是否懶加載 | 是否線程安全 | 優(yōu)點 | 缺點 | 適用場景 |
---|---|---|---|---|---|
懶漢式線程不安全 | 是 | 否 | 實現(xiàn)簡單 | 非線程安全 | 不建議使用 |
懶漢式線程安全 | 是 | 是 | 實現(xiàn)簡單;第一次調(diào)用才初始化,避免內(nèi)存浪費 | 加鎖會影響效率 | 不建議使用 |
餓漢式 | 否 | 是 | 實現(xiàn)簡單;沒有加鎖,執(zhí)行效率高 | 類加載時就初始化,浪費內(nèi)存 | 默認情況下推薦使用(沒有懶加載需求,也不考慮反序列化) |
登記式/靜態(tài)內(nèi)部類 | 是 | 是 | 兼顧運行效率和懶加載需求 | / | 有懶加載需求情況下,默認使用方案 |
枚舉 | 是 | 是 | 實現(xiàn)簡單(面試的時候?qū)懘a可以快人一步,哈哈); 自動支持序列化機制 | 不能用反射調(diào)用私有構(gòu)造函數(shù) | Effective Java 作者 Josh Bloch 提倡的方式,感覺面試用的更多一些 |
使用ThreadLocal | 是 | 是 | 多了解一個知識點,ThreadLocal會為每一個線程提供一個獨立的變量副本,從而隔離了多個線程對數(shù)據(jù)的訪問沖突。 | 實現(xiàn)復(fù)雜 | 面試 |
使用CAS鎖 | 是 | 是 | 多了解一個知識點 | 實現(xiàn)復(fù)雜 | 面試 |
kotlin
(1)object關(guān)鍵字的餓漢模式
object Singleton{}
用as轉(zhuǎn)成字節(jié)碼再反編譯后的java代碼,可以看出是餓漢模式
public final class Singleton{
public static final Singleton INSTANCE;
private Singleton(){}
static {
Singletonvar0 = new Singleton();
INSTANCE = var0;
}
}
除了object實現(xiàn)餓漢模式之外,其他和java形式雷同。
C++
c++除了私有構(gòu)造函數(shù),還要注意賦值拷貝接口,內(nèi)存安全的問題
- 全局只有一個實例:static 特性,同時禁止用戶自己聲明并定義實例(把構(gòu)造函數(shù)設(shè)為 private)
- 線程安全
- 禁止賦值和拷貝(操作符重載)
- 用戶通過接口獲取實例:使用 static 類成員函數(shù)()
(1)線程安全,內(nèi)存安全的懶漢模式(智能指針,鎖)
#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){
//只有判斷指針為空的時候才加
//避免每次調(diào)用 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析構(gòu)時,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&); //拷貝構(gòu)造函數(shù),C++11之前delete的替代方案
//Singleton& operator=(const A&);//拷貝復(fù)制運算符,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)局部靜態(tài)變量 懶漢式模式(推薦方式)
#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特性:
- 通過局部靜態(tài)變量的特性保證了線程安全 (C++11, GCC > 4.3, VS2015支持該特性);
- 不需要使用共享指針,代碼簡潔;
- 注意在使用的時候需要聲明單例的引用 Single& 才能獲取對象。
(3)c++ call_once
在C++11中提供一種方法,使得函數(shù)可以線程安全的只調(diào)用一次。即使用std::call_once和std::once_flag。std::call_once是一種lazy load的很簡單易用的機制。實現(xiàn)代碼如下:
#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;
}