单件模式(Singleton)
单件模式是指类就一个且只有一个实例,其广泛的运用于软件设计中,我看到的很多游戏引擎都用到了单件模式,感觉上单件更像是全局变量的一种替代品,给外部提供了一个访问类内部函数的接口,看下面一个简单的例子
//
in .h file
class SingletonClass
{
public :
static SingletonClass * Get()
{
return m_self;
}
static void Create()
{
if ( ! m_self)
m_self = new SingletonClass;
}
static void Destroy()
{
if (m_self)
delete m_self;
}
private :
SingletonClass();
~ SingletonClass();
static SingletonClass * m_self;
}
// in .cpp file
SingletonClass * SingletonClass::m_self( 0 );
class SingletonClass
{
public :
static SingletonClass * Get()
{
return m_self;
}
static void Create()
{
if ( ! m_self)
m_self = new SingletonClass;
}
static void Destroy()
{
if (m_self)
delete m_self;
}
private :
SingletonClass();
~ SingletonClass();
static SingletonClass * m_self;
}
// in .cpp file
SingletonClass * SingletonClass::m_self( 0 );
这个是单件模式类的基本格式,有几点值得注意,首先,将构造和析构函数声明为私有函数,是为了防止其他对象实例的生成,然后声明三个基本函数,Create用来创建对象实例,Destroy用来销毁实例,Get用来得到此实例并通过它来访问类其他公共的成员方法,有时为了防止Get到一个空指针,可以这样写Get
static
SingletonClass
*
Get()
{
if ( ! m_self)
m_self = new SingletonClass;
return m_self;
}
{
if ( ! m_self)
m_self = new SingletonClass;
return m_self;
}
使用这个类非常简单
//
创建实例
SingletonClass::Create();
// 假设SingletonClass有一个成员函数A
SingletonClass::Get() -> A();
// 销毁实例
SingletonClass::Destroy();
SingletonClass::Create();
// 假设SingletonClass有一个成员函数A
SingletonClass::Get() -> A();
// 销毁实例
SingletonClass::Destroy();
当我们需要很多singleton的类时,我们可以声明一个template类作为父类,以后只要继承这个类就可以将一个类声明为singleton
//
in .h file
template < typename T >
class SingletonClass
{
public :
static T * Get()
{
return m_self;
}
static void Create()
{
if ( ! m_self)
m_self = new T;
}
static void Destroy()
{
if (m_self)
delete m_self;
}
private :
SingletonClass();
~ SingletonClass();
static T * m_self;
}
// in .cpp file
template < typename T >
T * SingletonClass::m_self( 0 );
// 声明一个新的singleton类
class MySingleton : public SingletonClass < MySingleton >
{}
template < typename T >
class SingletonClass
{
public :
static T * Get()
{
return m_self;
}
static void Create()
{
if ( ! m_self)
m_self = new T;
}
static void Destroy()
{
if (m_self)
delete m_self;
}
private :
SingletonClass();
~ SingletonClass();
static T * m_self;
}
// in .cpp file
template < typename T >
T * SingletonClass::m_self( 0 );
// 声明一个新的singleton类
class MySingleton : public SingletonClass < MySingleton >
{}
singleton是比较容易理解,比较容易运用的一种设计模式,按照惯例,我们来看一下它的UML图