0

just for the sake of experimentation, I'm playing with the singleton pattern. I was wondering if it could be possible to extend the usual singleton class

class A
{
  private:
     static A* m_instance;
     A();
  public:
     static A* GetInstance();
}

A::A(){ ...some code}
A* A::m_instance = NULL;
A* A::GetInstance()
{
   if( m_instance == NULL ) m_instance = new A();
   return m_instance;
}

to a "multiple singleton" class, something like

class B
{
   private:
     static vector<B*> m_instances;
     B();
   public:
     static B* GetInstance( unsigned int n = 0);
     static B* GetNewInstance();
}

B* B::GetInstance( int n)
{
   if( n < m_instances.size() ) return m_instances.at(n);
   //Create a new instance and append it to m_instances
   B * temp = new B();
   m_instances.push_back( temp );
   return temp;
}

B* B::GetNewInstance()
{
   B * temp = new B();
   m_instances.push_back( temp );
   return temp;
}

The main problem I find in this pattern is the implementation of the destructor, because each nstance contains the vector of the instances so, if I delete an instance, I delete also the vector containing all other instances.

Is it possible to make this work? Or is it just a wrong pattern, plain and simple?

Blackphoenix
  • 103
  • 1
  • 2
  • 9
  • A singleton should be about object lifetime not class design. – Simple Sep 26 '13 at 10:38
  • Looks to me like you just want to keep track of every instance of that class ever created... There's nothing wrong with that. It's used in some popular frameworks (for windowing, for example). In the destructor, just remove itself from the list. By the way, don't use vector, use a map so you can find it faster for removal. You may want to wrap it with a mutex in case instances get created and destroyed in different threads. What you have here is a window class (MFC,QT,WxWidget, etc. all use the same pattern for windows). – thang Sep 26 '13 at 10:54

2 Answers2

2

I assume you know that Singleton are smells of a bad design. See What is so bad about singletons?

To answer your question, you're right about the drawbacks of a "multiple singleton". A better design would be instead a singleton where the variable is a vector<A*>, or vector<unique_ptr<A>> if you're using C++11 (assuming each A can't be copied and needs to be instantiated once. Otherwise use vector<A>)

Community
  • 1
  • 1
CharlesB
  • 75,315
  • 26
  • 174
  • 199
1

because each nstance contains the vector of the instances so, if I delete an instance, I delete also the vector containing all other instances.

No the vector<B*> will exist once for all instances since you've declared it static.

Who should call delete of your instances when? Usually using your technique the destructors of the singleton instance(s) never will be called.

πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175