利用宏實現的一個singleton
代碼:uniobj.h
2 *
3 * Created by kusamba@126.com at 2009-2-12 16:37
4 */
5
6 #ifndef _uniobj_23593953_h_
7 #define _uniobj_23593953_h_
8
9 #include <WTypes.h>
10 #include <assert.h>
11
12 /**
13 * Universal Object Declare
14 */
15 #define UNIOBJ_DECL(theClass) \
16 public: \
17 static theClass* Get() \
18 { \
19 assert(NULL != ms_pk##theClass); \
20 return ms_pk##theClass; \
21 } \
22 static theClass* Create() \
23 { \
24 assert(NULL == ms_pk##theClass); \
25 return ms_pk##theClass = new theClass(); \
26 } \
27 static void Destroy() \
28 { \
29 if (NULL != ms_pk##theClass) \
30 { \
31 delete ms_pk##theClass; \
32 ms_pk##theClass = NULL; \
33 } \
34 } \
35 public: bool Initialize(); \
36 private: \
37 theClass(); \
38 virtual ~theClass(); \
39 static theClass* ms_pk##theClass;
40
41 /**
42 * Universal Object Implement
43 */
44 #define UNIOBJ_IMP(theClass) \
45 theClass* theClass::ms_pk##theClass = NULL;
46
47
48 #endif//_uniobj_23593953_h_
如何使用:
頭文件:

2

3

4

5

6

7

8

cpp文件:

2

ATestSingleTon::ATestSingleTon()
{}
ATestSingleTon::~ATestSingleTon()
{}
3

4

5

6

main.cpp

2

3

4

5

6

7

8

9


10

11

12

分析:
1,singleton的構建在程序入口,析構在程序的結尾,可以避免相當多的多線程問題
2,這里的singleton對象均為程序必須要用到的對象,跟傳統singleton定義有些出入
3,定義了initialize()函數只為對象的初始化提供一個接口,如果不需要可以直接return true
PS:可以參考看看如下資料
1,細說Singleton模式:創建、多線程與銷毀 http://developer.51cto.com/art/200908/143492.htm
posted on 2010-08-31 15:56 iKusamba 閱讀(1489) 評論(10) 編輯 收藏 引用 所屬分類: C++技術