class Singleton {
private:
static Singleton* instance;
Singleton() {} // 私有構造函數,這樣外部無法使用此構造函數來創建多個實例
public:
// 刪除複製構造函數和賦值操作,確保不能複製此類的實例
Singleton(Singleton &other) = delete;
void operator=(const Singleton &) = delete;
// 獲取 Singleton 類的唯一實例的靜態函數
static Singleton* getInstance() {
if (instance == nullptr) { // 如果還沒有創建實例,則創建一個 (Lazy-Init 的概念)
instance = new Singleton();
}
return instance;
}
// 示範
void showMessage() {
std::cout << "Hello, this is Singleton!" << std::endl;
}
};
// 初始化靜態 Pointer 為 nullptr
Singleton* Singleton::instance = nullptr;
int main() {
// 試圖獲取 Singleton 的實例
Singleton* single = Singleton::getInstance();
single->showMessage(); // 應該顯示 "Hello, this is Singleton!"
}
[1]. https://shengyu7697.github.io/cpp-singleton-pattern/
[2]. https://ithelp.ithome.com.tw/articles/10225413
[3]. https://refactoring.guru/design-patterns/singleton