懒汉式,只有对象调用时,才创建对象
饿汉式程序运行自动创建对象
//饿汉式
class singleton_hungry
{
public://2、提供公共静态函数接口,其他类调用该类只能通过该接口
static singleton_hungry* getInstance()
{
return pSingleton;
}
private:
singleton_hungry() {
}// 1、构造函数私有化,其他类不可调用(Protected继承后也可用)
static singleton_hungry *pSingleton;
};
singleton_hungry *singleton_hungry::pSingleton = new singleton_hungry;//3、类外创建变量,static关键值可以通过域名创建对象
//懒汉式
class singleton_lazy
{
public://2、提供公共静态函数接口,其他类调用该类只能通过该接口
static singleton_lazy* getInstance()
{
if (pSingleton == NULL)
{
pSingleton = new singleton_lazy;
}
return pSingleton;
}
private:
singleton_lazy() {}// 1、构造函数私有化,其他类不可调用(Protected继承后也可用)
static singleton_lazy *pSingleton;
};
singleton_lazy *singleton_lazy::pSingleton = new singleton_lazy;//3、类外创建变量,static关键值可以通过域名创建对象