你肯定被面过这样一个问题:C++中如何实现一个类只能实例化一个对象?
单例模式可以保证一个类只能实例化一个对象!单例模式的核心结构中只包含一个被称为单例的特殊类。
防止用户随意的调用构造函数,将类的构造函数写成私有的,给用户提供返回对象的方法,在调用时不能依赖对象。
- 版本一: 懒加载(不论是否使用,都要初始化)
class Singleton
{
public:
static Singleton& getInstance()
{
return singlenton;
}
private:
Singleton() {};
static Singleton singlenton;
};
Singleton Singleton::singlenton = Singleton::getInstace() ;
//不论是否使用,程序运行后,对象已存在
- 版本二:快加载(使用时候才初始化)
class Singleton
{
public:
static Singleton* getInstance()
{
if(psingleTon == NULL)
{
psingleTon =