Singleton pattern
Singleton模式在维基百科上的定义如下:
In computer science, the singleton design pattern is designed to restrict instantiation of aclass to one (or a few) objects. This is useful when exactly one object is needed to coordinate actionsacross the system. Sometimes it is generalized to systems that operate moreefficiently when only one or a few objects exist. It is also considered an Anti-patternsince it is often used as a politically correct term for global variable -andhence frowned upon.
翻译成中文如下:
Singleton模式是用于限制类的实例对象个数到一个(或一些)。系统中当需要一个具有特定的功能的对象时比较有用,因为有时当只有一个或者有限个的对象存在是系统运行的效率比较高。同样也因为全局特性被看成是Anti- pattern!
可以说这个解释是相当完美的,如下提供代码的实现来看看具体的功能特性。
[code = cpp]
// singleton.cpp
# include <iostream>
using namespace std;
template <typename _Tp>
class Singleton
{
public:
typedef _Tp value_type;
~Singleton()
{
if(_instance != NULL)
{
delete_instance;
_instance =NULL;
}
}
// singleton implement
// tip: the retrieved variableshould be a pointer instead of a reference
// if so all the things wouldrefer to the singleton rather than assignment of which
//static Singleton&instance()
static Singleton* instance()
{
if(_instance == NULL)
{
_instance = newSingleton();
}
//if(_instance != NULL)
//{
// return *_instance;
//}
return _instance;
}
_Tp& data()
{
return _data;
}
private:
static Singleton * _instance;
private:
Singleton(){}
Singleton& operator=(const Singleton&){}
private:
_Tp _data;
};
template <typename _Tp>
Singleton<_Tp> * Singleton<_Tp>::_instance = NULL;
void main()
{
// Singleton<int> sngltn= Singleton<int>::instance();
// theSingleton<int>::instance() impls as following within class singleton
// static Singleton&instance() { // ... }
// this line calls instance()and initializes sngltn just as default assignment
// which means modificationson sngltn won't affect the singleton instance.
Singleton<int> * ps1 =Singleton<int>::instance();
ps1->data() = 1;
Singleton<int> * ps2 =Singleton<int>::instance();
ps2->data() = 2;
cout << ps1->data()<< endl; // output ”2” interminer
}
[/code]
从代码可以看出在main中使用时不需要了解有多少个指针引用了The Singleton Object只需要调用instance()就可以引用了。但是正如定义中指出,The Singleton Object具有全局特性不同的地方引用时使用的是同一个对象那么就会出现一个安全隐患!
本人在实现的过程中是通过使用模板来实现泛化的,此外还添加了 associated type特性只要对模板类进行特化基本上就可以添加到自己的STL中了。
那么就剩下最后一个问题了:用Singleton来实现什么功能呢?这个问题先留着。