从单例模板继承

时间:2011-10-20 14:22:24

标签: c++ templates singleton

我正在查看一个开源库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>;
}

这是一个好设计吗?这个设计有什么优势? 谢谢。

CV

1 个答案:

答案 0 :(得分:4)

如果你需要在某个全局的地方找到一个类的实例,那么每个人都可以看到它,然后创建一个实例并将它放在每个人都可以看到的地方。让类知道它将存在多少个实例并限制该类的基本用法是不好的设计。

我不止一次地看到,在项目开始时看起来像单身的一个类在项目结束时几乎没有实例。

相关问题