c++單例模式[1]--懶漢式基礎版
阿新 • • 發佈:2018-12-14
單例模式 基本版–單執行緒
#pragma once #include <iostream> #include <thread> /** *單例模式標準實現 5步走(懶漢式) 1靜態私有例項指標 2拷貝賦值私有化 3構造析構私有化 4全域性訪問與釋放 5靜態內部例項指標全域性例項 *Date :[10/9/2018 ] *Author :[RS] */ using namespace std; class Singleton1 { private: Singleton1() { cout << "構造 begin" << endl; this_thread::sleep_for(chrono::seconds(1)); cout << "構造 over" << endl; } virtual ~Singleton1() { cout << "構造" << endl; } private: Singleton1(const Singleton1&) = delete; Singleton1& operator=(const Singleton1) = delete; public: static Singleton1* GetInstance() { if (nullptr == mInstance) { mInstance = new Singleton1; } return mInstance; } static void RelaceInstance() { if (nullptr != mInstance) { delete mInstance; mInstance = nullptr; } } public: void print() { cout << "列印例項記憶體指標:" << mInstance << endl;; } private: static Singleton1 * mInstance; }; Singleton1* Singleton1::mInstance = NULL;
測試方法
#include "Singleton1.hpp"
void main() {
auto ss = Singleton1::GetInstance();
ss->print();
auto ss2 = Singleton1::GetInstance();
ss2->print();
system("pause");
}
測試結果