<<< Pattern One: Singleton     Index     Extending Singleton >>>

9. Implementing singletons

  • 
    class Singleton {
    public:
        static Singleton* get_singleton();
        //...
    
    protected:
        Singleton();
    
    private:
        static Singleton* m_ptr;
    };// class Singleton
    
    Singleton* Singleton::m_ptr = NULL;
    
    Singleton* Singleton::get_singleton()
    {
        if ( m_ptr == NULL )
            m_ptr = new Singleton;
        return m_ptr;
    }
    
    
  • Singleton details:

    • Constructor is protected to prevent multiple instances.

    • Lazy creation avoids two problems with initialization:

      1. Unknown order of get_singleton( ) calls

      2. Might need some run-time information for proper initialization.

  • What if we also need to control deallocation?

<<< Pattern One: Singleton     Index     Extending Singleton >>>