posts - 183,  comments - 10,  trackbacks - 0
来自于《大话设计模式》
单例模式(Singleton):保证一个类仅有一个实例,并提供访问它的全局访问点。类的实例化有类本身管理。

UML 类图:


代码实现 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 阅读(217) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理