虽然说游戏中涉及到的设计模式种类比较少,但是单例这种模式却随处可见,采用单例模式的类使用起来很方便。因为单例使用的比较多,所以如果每次使用单例时,都重新设计一下类结构,书写相关代码,让该类成为单例模式,这种方式会显得有些冗余,故抽象出来一个单例模板父类就比较快捷而优雅了。如果要使某个类成为单例模式,只需要继承该模板类就可以了。一种单例模板写法如下:
template <typename T>
class Singleton
{
protected:
static T* _instance;
Singleton() {}
virtual ~Singleton(){_instance = NULL;}
public:
static T& get_instance()
{
if (_instance == NULL) {
_instance = new T();
}
return *_instance;
}
}
template<typename T>
T* Singleton<T>::_instance = NULL;
假如要设计一个单例类Test, 则只需使用以下代码即可:
class Test : public Singleton<Test>
{
...
}
然后使用Test::get_instance().×××,即可调用该单例中的成员,这种实现方式看起来就要简洁优美些。