// example13.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "string.h"
#include "windows.h"
/*
我們的應用程序往往有許多配置項,而應用的配置項往往在每個類中都要用到,
所以把配置數量規整到一個類中來吧。然後用單例模式來實現。
*/
class config
{
private:
config()
{
};
config(const config& con)
{
};
config& operator= (const config& con)
{
};
public:
~config(){};
public:
static config* getInstance();
//*******************************************************************
};
//如果應用是單線程的就可以了,但是如果是多線程,不行需要加鎖來保護對
//getInstance 函數的調用。是線程之間互斥訪問getInstance。保障該函數作爲一個
//原語操作。
config* config::getInstance()
{
static config instance; //局部靜態變量太好了,不用考慮回收,並且在程序運行前就已經在堆區分配好內存了,
Sleep(100);
return &instance;
}
DWORD WINAPI WorkerThread(LPVOID)
{
for(int i=0; i<5; i++)
{
printf("threadid=%d pc=%08X\n", GetCurrentThreadId(), config::getInstance());
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
//測試一下吧,看是否只會產生一個實例
DWORD dwThreadId = 0;
for(int i=0; i<5; i++)
{
CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);
}
getchar();
return 0;
}
單件 singleton 唯一的對象實例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.