<<< Extending Singleton     Index     Disabling copy operations >>>

11. Extended singleton code

  • 
    class Singleton {
    public:
        static Singleton* get_singleton();
    
    protected:
        static void register_instance( string name, Singleton* ptr );
        Singleton();
    
    private:
        static Singleton* m_ptr;
        static map< string, Singleton* > m_registry;
    
    };//class Singleton
    
    Singleton* Singleton::m_ptr = NULL;
    
    Singleton* Singleton::get_singleton()
    {
        if ( m_ptr == NULL ) {
            string name = getenv( "SINGLETON" );
            m_ptr = m_registry[ name ];
        }
        return m_ptr;
    }
    
    void Singleton::register_instance( string name, Singleton* ptr )
    {
        m_registry[name] = ptr;
    }
    
    
  • Subclasses must register themselves with the base class.

  • Might do this using constructor for new class together with single static object.

  • This does introduce possible startup sequence problems if using multiple compilation units.

  • To avoid this, one needs an explicit switch in get_singleton( ), but still no new client code.

<<< Extending Singleton     Index     Disabling copy operations >>>