目的:怎样去创建一个唯一的变量(对象)?在基于对象的设计中我们可以通过创建一个全局变量(对象)来实现,在面向对象和面向过程结合的设计范式(如C++中)中,我们也还是可以通过一个全局变量实现这一点。但是当我们遇到了纯粹的面向对象范式中,这一点可能就只能是通过Singleton模式来实现了。
注意:
1. 在默认构造函数Singleton()访问类型是protected(或private)
2. public: static Singleton* Instance();
3. private: static Singleton* _instance;
4. Singleton* Singleton::_instance = 0;
5.Singleton *sgn = Singleton::Instance();
代码(来自设计模式精解-Gof 23 种设计模式解析), 在VS2010上调试通过
//Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
#endif
//Singleton.cpp
#include "Singleton.h"
Singleton* Singleton::_instance = 0;
Singleton::Singleton()
{
std::cout<<"Singleton ..."<<std::endl;
}
Singleton* Singleton::Instance()
{
if(0 == _instance)
{
_instance = new Singleton();
}
return _instance;
}
//main.cpp
#include "Singleton.h"
int main(int argc, char* argv[])
{
Singleton *sgn = Singleton::Instance();
delete sgn;
sgn = 0;
system("pause");
return 0;
}