1 #include<iostream>
2 using namespace std;
3 #include<string>
4
5 //单例模式
6 //控制某个对象个数,只有一个
7
8 //实现单例的步骤
9 //1.构造函数的私有化
10 //2.增加静态私有的当前类指针
11 //3.提供静态的对外接口,可以让用户获得单例对象
12
13 //单例分为懒汉式和饿汉式,在类外初始化的时候可看出不同
14
15 //懒汉式是多线程不安全的,因为在getInstance那里可能创建多个类
16
17 //懒汉式
18 class singleton_lazy{
19 private:
20 singleton_lazy(){
21 cout<<"lazy"<<endl;
22 }
23 static singleton_lazy* sl;
24 public:
25 static singleton_lazy* getInstance(){
26 if(sl==NULL){
27 sl=new singleton_lazy;
28 }
29 return sl;
30 }
31 };
32 //类外初始化
33 singleton_lazy* singleton_lazy::sl=NULL;
34
35
36 //饿汉式
37 class singleton_hungry{
38 private:
39 singleton_hungry(){
40 cout<<"hungry"<<endl;
41 }
42 static singleton_hungry* sh;
43 public:
44 static singleton_hungry* getInstance(){
45 return sh;
46 }
47 };
48 //类外初始化
49 singleton_hungry* singleton_hungry::sh=new singleton_hungry;
50
51
52 void test1()
53 {
54 singleton_lazy* p1=singleton_lazy::getInstance();
55 singleton_lazy* p2=singleton_lazy::getInstance();
56 if(p1==p2){
57 cout<<"lazy is singleton"<<endl;
58 }
59 else{
60 cout<<"lazy is not singleton"<<endl;
61 }
62
63 singleton_hungry* p3=singleton_hungry::getInstance();
64 singleton_hungry* p4=singleton_hungry::getInstance();
65 if(p3==p4){
66 cout<<"hungry is singleton"<<endl;
67 }
68 else{
69 cout<<"hungry is not singleton"<<endl;
70 }
71 }
72 int main()
73 {
74 test1();
75 cout<<"main"<<endl;
76 return 0;
77 }