1 单例模式有两种: 饿汉式及懒汉式。
2 懒汉式存在多线程问题需要加锁。
class singleton
{
private:
singleton(){}
public:
static singleton* getInstance();
private:
static singleton* m_psl;
};
singleton* singleton::getInstance()
{
if (m_psl == NULL)
{
//pthread_mutex_lock(&mutex);
if (m_psl == NULL)
{
singleton* tmp = new singleton;
m_psl = tmp;
}
//pthread_mutex_unlock(&mutex);
}
return m_psl;
}
singleton* singleton::m_psl = NULL;//懒汉式
//singleton* singleton::m_psl = singleton::getInstance(); //饿汉式
//singleton *singleton::m_psl = new singleton; //饿汉式