从单例模板继承
我正在查看一个开源库 VLMC,并发现了这个单例的实现。其完成方式是,为了创建一个单例类“Library”,Library 是从 Singleton 继承的。像这样
// SINGLETON_HPP
template <typename T>
class Singleton
{
//regular singleton implementation
protected:
Singleton(){}
virtual ~Singleton(){}
};
template <typename T>
T* Singleton<T>::m_instance = NULL;
// LIBRARY_H_
class Library : public Singleton<Library>
{
//some other stuff
private:
Library();
virtual ~Library(){}
friend class Singleton<Library>;
}
这是一个好的设计吗?这种设计有什么优点? 谢谢。
简历
I was looking at an opensource library VLMC and found this implementation of a singleton. The way it is done is, for creating a singleton class 'Library', Library was inherited from a Singleton. Like this
// SINGLETON_HPP
template <typename T>
class Singleton
{
//regular singleton implementation
protected:
Singleton(){}
virtual ~Singleton(){}
};
template <typename T>
T* Singleton<T>::m_instance = NULL;
// LIBRARY_H_
class Library : public Singleton<Library>
{
//some other stuff
private:
Library();
virtual ~Library(){}
friend class Singleton<Library>;
}
Is this a good design? And what advantages does this design provide?
Thank you.
CV
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您需要某个类的一个实例位于每个人都可以看到的全局位置,那么创建一个实例并将其放在每个人都可以看到的地方。让类知道它将存在多少个实例并限制类的基本使用是糟糕的设计。
我不止一次地看到,一个在项目开始时看起来像单例的类在项目结束时几乎没有实例。
If you need one instance of a class in some global place where everybody see it, then create one instance and put it somewhere everybody can see it. It is bad design to make the class know how many instances of it will exist and limit basic usage of the class.
I've seen more than once that a class that seemed like a singleton at the beginning of the project had few instances at the end of the project.