剑指offer学习摘录-面试2 单例模式

 书上是c#的解法,我得用c++呀,所以就自己写一个。

要点:

  • 构造函数设为private。
  • 静态函数注意多线程。

代码:

 1 #include<iostream>
 2 #include<Windows.h> // in order to use critical section
 3 using namespace std;
 4 
 5 class Singleton
 6 {
 7 public:
 8     ~Singleton()
 9     {
10     };
11     static void InitAll();
12     static void ReleaseAll();
13 
14     Singleton(const Singleton&) = delete;
15     static Singleton* GetInstance();
16     Singleton* operator= (const Singleton&) = delete;
17 
18 private:
19     Singleton()
20     {
21     }
22 
23     static Singleton* m_pInstance;
24     static CRITICAL_SECTION m_CS;
25 };
26 
27 Singleton* Singleton::m_pInstance;
28 CRITICAL_SECTION Singleton::m_CS;
29 
30 void Singleton::InitAll()
31 {
32     InitializeCriticalSection(&m_CS);
33     cout << "init section" << endl;
34     m_pInstance = NULL;
35 }
36 
37 void Singleton::ReleaseAll() //类的构造函数是静态的,析构函数也得显示程序员自己调用
38 {
39     if (m_pInstance)
40         delete m_pInstance;
41     DeleteCriticalSection(&Singleton::m_CS);
42     cout << "delete myself" << endl;
43 }
44 
45 Singleton* Singleton::GetInstance()
46 {
47     if (Singleton::m_pInstance == NULL)
48     {
49         EnterCriticalSection(&m_CS);
50         if (Singleton::m_pInstance == NULL)
51         {
52             cout << "first create" << endl;
53             Singleton::m_pInstance = new(std::nothrow) Singleton();
54         }
55         else
56         {
57             cout << "already" << endl;
58         }
59         LeaveCriticalSection(&m_CS);
60     }
61     else
62     {
63         cout << "already 2" << endl;
64     }
65     return Singleton::m_pInstance;
66 }
67 
68 
69 
70 void main()
71 {
72     Singleton::InitAll();
73     Singleton* a = Singleton::GetInstance();
74     Singleton* b = Singleton::GetInstance();
75     Singleton* c = Singleton::GetInstance();
76     Singleton* d = Singleton::GetInstance();
77     Singleton* e = Singleton::GetInstance();
78     Singleton* f = Singleton::GetInstance();
79     Singleton::ReleaseAll();
80 }

 运行结果:

 

posted @ 2022-02-09 17:45  Joanna-In-Hdu&Hust  阅读(30)  评论(0编辑  收藏  举报