单例模式:将构造函数声明为私有的,这样就不能被外部调用构造函数来构造对象了,甚至可以将析构函数也声明为私有的,这样就只有自己能够删除自己了。
保证一个类只有一个实例,对外提供一个访问它的全局访问点。
//方式一
class Singleton
{
public:
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
private:
Singleton()
{
cout << "Singleton()" << endl;
}
~Singleton()
{
cout << "~Singleton()" << endl;
}
};
//方式二
class Singleton
{
public:
static Singleton* getInstance()
{
return &instance;
}
private:
Singleton()
{
cout << "Singleton()" << endl;
}
~Singleton()
{
cout << "~Singleton()" << endl;
}
static Singleton instance;
};
Singleton Singleton::instance;
int main(int argc, char *argv[])
{
cout << Singleton::getInstance() << endl;
cout << Singleton::getInstance() << endl;
cout << Singleton::getInstance() << endl;
return 0;
}
//方式三
class Singleton
{
public:
static Singleton* getInstance()
{
if(instance == NULL)
instance = new Singleton();
return instance;
}
~Singleton()
{
cout << "~Singleton()" << endl;
}
private:
Singleton()
{
cout << "Singleton()" << endl;
}
static Singleton *instance;
};
Singleton *Singleton::instance = NULL;
int main(int argc, char *argv[])
{
cout << Singleton::getInstance() << endl;
cout << Singleton::getInstance() << endl;
cout << Singleton::getInstance() << endl;
delete Singleton::getInstance();
return 0;
}
详情请点击:https://www.cnblogs.com/xiehongfeng100/p/4781013.html