單例模式是軟件設計模式中最簡單也是最常用的一種創建型設計模式。它的核心目標是確保一個類在整個應用程序生命周期中只有一個實例,并提供一個全局訪問點。
筆者白話版理解:你創建了一個類,如果你希望這個類對象在工程中應用時只創建一次,不能多次創建,比如:TCP通信時,通信模式為一對多,只能有一個服務器,而客戶端可以有多個,那么你在創建服務器類時,就可以使用單例模式,這樣就可以保證工程中只會有一個服務器。
核心概念
三大要點
- 私有化構造函數?- 防止外部直接創建實例
- 私有化拷貝構造函數和賦值操作符?- 防止實例被復制
- 提供全局訪問的靜態方法?- 獲取唯一的實例
主要特點
唯一實例:保證一個類只有一個實例存在
全局訪問:提供統一的訪問接口
延遲初始化:實例在第一次使用時才被創建
線程安全:在多線程環境下也能保證唯一性
話不多說,直接上例子
基于Qt的應用:
// LaserStabilizeWin.h文件class LaserStabilizeWin : public QWidget
{Q_OBJECT
public:static LaserStabilizeWin* instance();static void disinstance();private:explicit LaserStabilizeWin(QWidget *parent = nullptr); //私有化構造函數~LaserStabilizeWin();
};
// LaserStabilizeWin.cpp#include "LaserStabilizeWin.h"LaserStabilizeWin* LaserStabilizeWin::m_pInstance = NULL; //靜態成員定義
LaserStabilizeWin *LaserStabilizeWin::instance()
{if (m_pInstance == NULL){m_pInstance = new LaserStabilizeWin(NULL);}return m_pInstance;
}void LaserStabilizeWin::disinstance()
{delete m_pInstance;m_pInstance = nullptr;
}LaserStabilizeWin::LaserStabilizeWin(QWidget *parent) : QWidget(parent)
{qDebug()<<"構造函數";
}LaserStabilizeWin::~LaserStabilizeWin()
{qDebug()<<"析構函數";
}
在純C++開發中的應用,和上面的區別不大:
class BestSingleton {
public:static BestSingleton& getInstance() {static BestSingleton instance;return instance;}// 業務方法...private://私有化構造函數和析構函數 BestSingleton() = default;~BestSingleton() = default;BestSingleton(const BestSingleton&) = delete;BestSingleton& operator=(const BestSingleton&) = delete;
};
使用場景
資源共享:如數據庫連接池、線程池
配置管理:全局配置信息
日志記錄:統一的日志系統
緩存系統:全局緩存管理
設備控制:如打印機、硬件設備控制