单例模式
- 保证一个类只有一个实例,并提供一个全局访问点
- 禁止拷贝
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance()
{
if (instacne_ == NULL)
{
instacne_ = new Singleton;
}
return instacne_;
}
~Singleton()
{
cout<<"~Singleton ..."<<endl;
}
private:
Singleton(const Singleton& other);
Singleton& operator=(const Singleton& other);
Singleton()
{
cout<<"Singleton ..."<<endl;
}
static Singleton* instacne_;
};
Singleton* Singleton::instacne_;
int main(void)
{
Singleton* s1 = Singleton::GetInstance();
return 0;
}
将拷贝构造函数和构造函数声明为使用,赋值声明为私有。但上面的代码没有释放对象
解决方法一:声明一个静态Free函数
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance()
{
if (instacne_ == NULL)
{
instacne_ = new Singleton;
}
return instacne_;
}
~Singleton()
{
cout<<"~Singleton ..."<<endl;
}
static void Free()
{
if (instacne_ != NULL)
{
delete instacne_;
}
}
private:
Singleton(const Singleton& other);
Singleton& operator=(const Singleton& other);
Singleton()
{
cout<<"Singleton ..."<<endl;
}
static Singleton* instacne_;
};
Singleton* Singleton::instacne_;
int main(void)
{
Singleton* s1 = Singleton::GetInstance();
Singleton* s2 = Singleton::GetInstance();
Singleton::Free();
return 0;
}
缺点:当程序较复杂市在哪里释放不好确定,应该让其自动释放
解决方法:定义一个嵌套类,
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance()
{
if (instacne_ == NULL)
{
instacne_ = new Singleton;
}
return instacne_;
}
~Singleton()
{
cout<<"~Singleton ..."<<endl;
}
class Garbo
{
public:
~Garbo()
{
if (Singleton::instacne_ != NULL)
{
delete instacne_;
}
}
};
private:
Singleton(const Singleton& other);
Singleton& operator=(const Singleton& other);
Singleton()
{
cout<<"Singleton ..."<<endl;
}
static Singleton* instacne_;
static Garbo garbo_; // 利用对象的确定性析构
};
Singleton::Garbo Singleton::garbo_;
Singleton* Singleton::instacne_;
int main(void)
{
Singleton* s2 = Singleton::GetInstance();
return 0;
}
方案三:声明一个局部静态对象 (不是线程安全)
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton& GetInstance()
{
static Singleton instance; // 局部静态对象
return instance;
}
~Singleton()
{
cout<<"~Singleton ..."<<endl;
}
private:
Singleton(const Singleton& other);
Singleton& operator=(const Singleton& other);
Singleton()
{
cout<<"Singleton ..."<<endl;
}
};
int main(void)
{
Singleton& s1 = Singleton::GetInstance();
Singleton& s2 = Singleton::GetInstance();
return 0;
}
方案四:待续