单例模式

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #include <iostream>
 5 #include <limits.h>
 6 using namespace std;
 7 
 8 class Singleton
 9     {
10         private:
11             Singleton(){}//构造函数私有化
12             static Singleton *m_pInstance;
13         public:
14             static Singleton *GetInstance()
15             {
16                 static Singleton *m_pInstance;
17                 if(m_pInstance==NULL)
18                     m_pInstance = new Singleton();
19                 return m_pInstance;
20             }
21             int test()
22             {
23                 return 2;
24             }
25     };
26 
27 int main()
28 {
29     Singleton *p1 = Singleton::GetInstance();
30     Singleton *p2 = p1->GetInstance();
31     int a;
32     a=p2->test();
33     cout<<a;
34     return 0;
35 }

单例模式的目的是保证这个类只有一个实例。

 

更加详细:http://blog.csdn.net/hackbuteer1/article/details/7460019

posted @ 2015-05-11 00:03  niceforbear  阅读(59)  评论(0)    收藏  举报