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?