C++单例模式
01 //单例模式
02 //main.cc
03 #include "Single.h"
04
05 #include <iostream>
06 using namespace std;
07
08 int main(int argc, char *argv[])
09 {
10 Single::GetInstance();
11 Single::GetInstance();
12 return 0;
13 }
14
15 //Single.h
16 class Single
17 {
18 public:
19 static Single &GetInstance();
20 private:
21 Single();
22 Single(const Single &);
23 Single &operator = (const Single &);
24 };
25
26 //Single.cpp
27 #include "Single.h"
28
29 #include <iostream>
30
31 using namespace std;
32
33 Single &Single::GetInstance()
34 {
35 static Single instance;
36 return instance;
37 }
38
39 Single::Single()
40 {
41 cout<<"Hello,this your world!" <<endl;
42 }
43
44 虽然 main 函数中调用了两次 Single::GetInstance();
45 但只有一次 “Hello,this your world!”的输出,也就是单例模式成功了!
46
47
48 //其它的实现方式!
49 #include <iostream>
50
51 using namespace std;
52
53 class Single
54 {
55 private:
56 Single();
57 virtual ~Single();
58 static Single *instance;
59
60 public:
61 static Single *GetInstance();
62 };
63
64 Single::Single()
65 {
66 cout<<"Hello,this your world!" <<endl;
67 }
68
69 Single::~Single()
70 {
71 delete instance;
72 }
73
74 Single *Single::instance = new Single();
75 Single *Single::GetInstance()
76 { www.zzzyk.com
77 return instance;
78 }
79
80 int main(int argc, char *argv[])
81 {
82 Single *single1 = Single::GetInstance();
83 Single *single2 = Single::GetInstance();
84
85 return 0;
86 }
作者:雲瑜
补充:软件开发 , C++ ,