diff --git a/6.SingletonPattern/1.Picture/单例模式.vsdx b/6.SingletonPattern/1.Picture/单例模式.vsdx new file mode 100644 index 0000000..63881e9 Binary files /dev/null and b/6.SingletonPattern/1.Picture/单例模式.vsdx differ diff --git a/6.SingletonPattern/1.Picture/单例模式UML图.png b/6.SingletonPattern/1.Picture/单例模式UML图.png new file mode 100644 index 0000000..df48d4e Binary files /dev/null and b/6.SingletonPattern/1.Picture/单例模式UML图.png differ diff --git a/6.SingletonPattern/2.Code/Singleton/Singleton.h b/6.SingletonPattern/2.Code/Singleton/Singleton.h new file mode 100644 index 0000000..3ff8a6a --- /dev/null +++ b/6.SingletonPattern/2.Code/Singleton/Singleton.h @@ -0,0 +1,33 @@ +#ifndef __SINGLETON_H__ +#define __SINGLETON_H__ + +#include +#include +#include +using namespace std; + +class Singleton +{ +public: + static Singleton* getInstance(){ + if (instance == NULL){ + m_mutex.lock(); + if (instance == NULL){ + printf("µʵ\n"); + instance = new Singleton(); + } + m_mutex.unlock(); + } + return instance; + } +private: + Singleton(){} + + static Singleton* instance; + static std::mutex m_mutex; +}; + +Singleton* Singleton::instance = NULL; +std::mutex Singleton::m_mutex; + +#endif //__SINGLETON_H__ \ No newline at end of file diff --git a/6.SingletonPattern/2.Code/Singleton/main.cpp b/6.SingletonPattern/2.Code/Singleton/main.cpp new file mode 100644 index 0000000..bee839c --- /dev/null +++ b/6.SingletonPattern/2.Code/Singleton/main.cpp @@ -0,0 +1,50 @@ +#include +#include "Singleton.h" + +/*ģʽʵ*/ +/* +int main() +{ + Singleton *s1 = Singleton::getInstance(); + Singleton *s2 = Singleton::getInstance(); + + system("pause"); + return 0; +} +*/ + +/*̰߳ȫ ģʽ*/ +#include +#include + +//̣߳߳Ŀ5 +#define THREAD_NUM 5 + +unsigned int __stdcall CallSingleton(void *pPM) +{ + Singleton *s = Singleton::getInstance(); + int nThreadNum = *(int *)pPM; + Sleep(50); + //printf("̱߳Ϊ%d\n", nThreadNum); + return 0; +} + + +int main() +{ + HANDLE handle[THREAD_NUM]; + + //̱߳ + int threadNum = 0; + while (threadNum < THREAD_NUM) + { + handle[threadNum] = (HANDLE)_beginthreadex(NULL, 0, CallSingleton, &threadNum, 0, NULL); + //߳̽յʱܸ߳̿ıiֵ + threadNum++; + } + //֤߳ȫн + WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE); + + system("pause"); + return 0; +} \ No newline at end of file diff --git a/README.md b/README.md index 49ea5f4..944c8c2 100644 --- a/README.md +++ b/README.md @@ -31,4 +31,8 @@ 08.设计模式(八)——原型模式 -博客地址:https://blog.csdn.net/sinat_21107433/article/details/102642682 \ No newline at end of file +博客地址:https://blog.csdn.net/sinat_21107433/article/details/102642682 + +09.设计模式(九)——单例模式 + +博客地址:https://blog.csdn.net/sinat_21107433/article/details/102649056 \ No newline at end of file