Codelite代码分析之 Singleton Pattern Template实现及应用
CodeLite中实现了一个简单的Singleton Pattern模板并有10个模块使用了它,通过源码我们可以看到它并没有考虑多线程安全和垃圾回收等。
Singleton Pattern的作用是保证一个类仅有一个实例,并提供一个访问它的全局访问点。Singleton模式其实是对全局静态变量的一个取代策略,上面提到的Singleton模式的两个作用在C++中是通过如下的机制实现的:1)仅有一个实例,提供一个类的静态成员变量,大家知道类的静态成员变量对于一个类的所有对象而言是惟一的 2)提供一个访问它的全局访问点,也就是提供对应的访问这个静态成员变量的静态成员函数,对类的所有对象而言也是惟一的.在C++中,可以直接使用类域进行访问而不必初始化一个类的对象。
在Codelite中也应用到了这个模式实现如下:
template <class T> class Singleton
{
static T* ms_instance;
public:
/**
* Static method to access the only pointer of this instance.
* \return a pointer to the only instance of this
*/
static T* Get();
/**
* Release resources.
*/
static void Free();
protected:
/**
* Default constructor.
*/
Singleton();
/**
* Destructor.
*/
virtual ~Singleton();
};
template <class T> T* Singleton<T>::ms_instance = 0;
template <class T> Singleton<T>::Singleton()
{
}
template <class T> Singleton<T>::~Singleton()
{
}
template <class T> T* Singleton<T>::Get()
{
if(!ms_instance)
ms_instance = new T();
return ms_instance;
}
template <class T> void Singleton<T>::Free()
{
if( ms_instance )
{
delete ms_instance;
ms_instance = 0;
}
}
Codelite中一共有如下十个模块使用了Singleton Pattern Template:
Buildmanager.h (codelite-1.0.2822\plugin):typedef Singleton<BuildManager> BuildManagerST;
Build_settings_config.h (codelite-1.0.2822\plugin):typedef Singleton<BuildSettingsConfig> BuildSettingsConfigST;
Cscopedbbuilderthread.h (codelite-1.0.2822\cscope):typedef Singleton< CscopeDbBuilderThread > CScopeThreadST;
Ctags_manager.h (codelite-1.0.2822\codelite):typedef Singleton<TagsManager> TagsManagerST;
Editor_config.h (codelite-1.0.2822\plugin):typedef Singleton<EditorConfig> EditorConfigST;
Language.h (codelite-1.0.2822\codelite):typedef Singleton<Language> LanguageST;
Manager.h (codelite-1.0.2822\liteeditor):typedef Singleton<Manager> ManagerST;
Parse_thread.h (codelite-1.0.2822\codelite):typedef Singleton<ParseThread> ParseThreadST;
Search_thread.h (codelite-1.0.2822\plugin):typedef Singleton<SearchThread> SearchThreadST;
Workspace.h (codelite-1.0.2822\plugin):typedef Singleton<Workspace> WorkspaceST;
Related posts:














