單例模式:保證整個工程中,有且只有一個該類的一個實例對象存在
//SingleObject.h
#ifndef _SINGLEOBJECT_H_ #define _SINGLEOBJECT_H_ #define SINGLEOBJECT single::instance(); //定義全局 單例對象變量 class single { public: static single * instance() //返回單例對象 { if(uniqueInstance==NULL) { uniqueInstance = new single(); } return uniqueInstance; } private: //類的外部不可創建對象 single();//構造函數 single(const single &);//拷貝構造函數 //single(const single &) = delete ; //禁用拷貝構造函數 private: static single * uniqueInstance;
public://for test
void test_func()
{
std::cout<<"單例對象創建成功"<<std::endl;
}
v }; #endif
1
//SingleObject.cpp
#include"SingleObject.h" single * single::uniqueInstance=NULL; single::single() {} single::single(const single&) {}
2
//main.cpp
#include "SingleObject.h" int main(int argc, char* argv[]) { //SINGLEOBJECT->text_func(); //使用報錯,還不知道原因 single * a = single::instance(); a->test_func();//調用成功 return 0; }
3
2018.3.22
注意:多線程中使用,需要修改 ,加:在instance函數中加雙重鎖