介紹
????????單例模式優(yōu)點(diǎn)是可以確保系統(tǒng)中只存在單個(gè)對象實(shí)例,缺點(diǎn)是不便擴(kuò)展,一定程度上違背單一原則,既提供業(yè)務(wù)方法,又提供創(chuàng)建對象方法
餓漢式單例
? ? ? ? 在類加載的時(shí)候就創(chuàng)建好對象,獲取對象時(shí)直接返回即可
class EagerSingleton {
public:
static EagerSingleton *getInstance() {
return m_inst;
}
private:
EagerSingleton() {}
static EagerSingleton *m_inst;
};
EagerSingleton *EagerSingleton::m_inst = new EagerSingleton();
懶漢式單例
? ? ? ? 在類加載的時(shí)候沒有創(chuàng)建對象,第一次獲取對象時(shí)根據(jù)需要創(chuàng)建對象并返回,此時(shí)需要考慮線程安全問題
class LazySingleton {
public:
static LazySingleton *getInstance() {
if (s_inst == NULL) {
std::lock_guard<std::mutex> lg(s_mtx);
if (s_inst == NULL) {
s_inst = new LazySingleton();
}
}
return s_inst;
}
private:
LazySingleton() {}
static LazySingleton *s_inst;
static std::mutex s_mtx;
};
LazySingleton *LazySingleton::s_inst = NULL;
std::mutex LazySingleton::s_mtx;
餓漢式和懶漢式對比
? ? ? ??文章來源:http://www.zghlxwxcb.cn/news/detail-785773.html
實(shí)現(xiàn)方式 | 優(yōu)點(diǎn) | 缺點(diǎn) |
餓漢式 | 簡單,無須考慮線程安全,調(diào)用速度快 | 無論是否需要都創(chuàng)建了對象,資源利用效率不高,導(dǎo)致系統(tǒng)啟動時(shí)間變長 |
懶漢式 | 系統(tǒng)啟動時(shí)間減少,可以延遲創(chuàng)建對象,提高資源利用效率 | 需要處理線程安全問題,初始化期間有可能影響系統(tǒng)性能 |
IoDH技術(shù)
? ? ? ? 應(yīng)該是java語言獨(dú)有的,不確定性能如何文章來源地址http://www.zghlxwxcb.cn/news/detail-785773.html
到了這里,關(guān)于《設(shè)計(jì)模式的藝術(shù)》筆記 - 單例模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!