单例模式
设计模式一定是先有需求然后有设计模式。
单例设计模式指一个类只能生成一个对象。如打印机对象
#include<iostream>
using namespace std;
class CSingleton
{
private:
CSingleton()
{
cout << "构造成功!" << endl;
}
static CSingleton *m_instance;
public:
static pthread_mutex_t mtx;
static CSingleton* getInstance()
{
if(p == NULL)
{
pthread_mutex_lock(&mtx);
m_instance = new CSingleton();
pthread_mutex_unlock(&mtx);
}
class CGarbushi:
{
~CGarbushi()
{
if(m_instance)
{
delete m_instance;
m_instance = NULL;
}
}
};
return m_instance;
}
};
//静态成员变量初始化
pthread_mutex_t CSingleton::mtx;
CSingleton* CSingleton::m_instance = NULL;
int main()
{
CSingleton *t = CSingleton::getInstance();
CSingleton *tt = CSingleton::getInstance();
//地址一致,说明t与tt是同一对象
cout << t << endl << tt << endl;
return 0;
}

浙公网安备 33010602011771号