#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdlib.h>
#include <windows.h>
using namespace std;
#if 1
/**
* 懒汉式
*/
class Singelton {
public:
static Singelton * getInstance()
{
if (m_sig == NULL)
{
m_sig = new Singelton();
}
return m_sig;
}
static void freeInstance()
{
if (m_sig != NULL)
{
delete m_sig;
m_sig = NULL;
}
//return m_sig;
}
private:
Singelton() {
Sleep(1000);
}
static Singelton * m_sig;
};
Singelton * Singelton::m_sig = NULL;
#endif
#if 0
/**
* 饿汉式
*/
class Singelton {
public:
static Singelton * getInstance()
{
return m_sig;
}
static void freeInstance()
{
if (m_sig != NULL)
{
delete m_sig;
m_sig = NULL;
}
//return m_sig;
}
private:
Singelton() {}
static Singelton * m_sig;
};
Singelton * Singelton::m_sig = new Singelton;
#endif
int main(void)
{
#if 0
Singelton *p = Singelton::getInstance();
Singelton *p1 = Singelton::getInstance();
Singelton::freeInstance();
cout << p << endl << p1 << endl;
#endif
#if 1
Singelton *p = Singelton::getInstance();
Singelton *p1 = Singelton::getInstance();
Singelton::freeInstance();
cout << p << endl << p1 << endl;
#endif
system("pause");
return EXIT_SUCCESS;
}
C++设计模式之单例模式
最新推荐文章于 2024-09-06 08:50:54 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)