#include <iostream>
using namespace std;
//单例模式全局只能有一个对象,注意:懒汉模式遇到多线程 需要创建一个互斥锁,使它线性执行
//懒汉
class Singelton {
public:
static Singelton* getInstance() {
//
if (NULL == instance)
{
instance = new Singelton;
}
//
++m_count;
return instance;
}
void show_count()
{
cout << m_count << endl;
}
private:
Singelton() {
instance = NULL;
m_count = 0;
cout << "懒汉模式" << endl;
}
public:
static Singelton* instance;
static int m_count;
};
int Singelton::m_count = 0;
Singelton* Singelton::instance = NULL;
//饿汉
class Singelton1 {
public:
static Singelton1* getInstance() {
++m_count;
return instance;
}
void show_count()
{
cout << m_count << endl;
}
private:
Singelton1() {
instance = NULL;
m_count = 0;
cout << "饿汉模式" << endl;
}
public:
static Singelton1* instance;
static int m_count;
};
int Singelton1::m_count = 0;
Singelton1* Singelton1::instance = new Singelton1;
int main()
{
Singelton* sp1 = Singelton::getInstance();
Singelton* sp2 = Singelton::getInstance();
if(sp1 == sp2)
{
cout << "懒汉相同" << endl;
}
else
{
cout << "懒汉不相同" << endl;
}
sp2->show_count();
Singelton1* sp3 = Singelton1::getInstance();
Singelton1* sp4 = Singelton1::getInstance();
if (sp3 == sp4)
{
cout << "饿汉相同" << endl;
}
else
{
cout << "饿汉不相同" << endl;
}
sp4->show_count();
return 0;
}
2种单例模式类型
最新推荐文章于 2022-03-31 14:07:57 发布