來(lái)自于《大話(huà)設(shè)計(jì)模式》
單例模式(Singleton):保證一個(gè)類(lèi)僅有一個(gè)實(shí)例,并提供訪(fǎng)問(wèn)它的全局訪(fǎng)問(wèn)點(diǎn)。類(lèi)的實(shí)例化有類(lèi)本身管理。
UML 類(lèi)圖:

代碼實(shí)現(xiàn) C++:
1 #include <iostream>
2 using namespace std;
3
4 class Singleton
5 {
6 private:
7 static Singleton* instance;
8 Singleton() {}
9 public:
10 static Singleton* GetInstance()
11 {
12 if (instance == 0)
13 {
14 instance = new Singleton;
15 }
16 return instance;
17 }
18 ~Singleton()
19 {
20 delete instance;
21 }
22 };
23
24 Singleton* Singleton::instance = 0;
25
26 int main()
27 {
28 Singleton* s1 = Singleton::GetInstance();
29 Singleton* s2 = Singleton::GetInstance();
30
31 cout << s1 << endl;
32 cout << s2 << endl;
33
34 return 0;
35 }
posted on 2011-04-29 17:09
unixfy 閱讀(229)
評(píng)論(0) 編輯 收藏 引用