这一节是简单的单例模式,顾名思义也就是说一个类只能有一个对象。我们通过维护一个static的成员来记录这个唯一的对象实例。
把构造函数设为私有的,只能通过GetInstance来获得该类的实例
两种实现方法
class Singleton
{
public:
static Singleton* GetInstance()
{
static Singleton instance;
return &instance;
}
void method()
{
cout<<i++<<endl;
}
private:
Singleton()
:i(0){}
private:
int i;
};
//或者
class Singleton
{
public:
static Singleton* GetInstance()
{
if (!m_instance)
{
m_instance = new Singleton;
}
return m_instance;
}
void method()
{
cout<<i++<<endl;
}
private:
Singleton()
:i(0){}
private:
int i;
static Singleton* m_instance;
};
int _tmain(int argc, _TCHAR* argv[])
{
Singleton::GetInstance()->method();
Singleton::GetInstance()->method();
return 0;
}
全局变量可能进行多次实例化,而单例模式则是直接将其封死。
单例模式还是比较简单的,这里就不赘述了。