我正在玩单身人士模式。我在想,如果它可能是可能为了实验的缘故,伪单身人员类别的多个实例
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;
}
延长通常单件类的“多单”类,像
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;
}
主要的问题,我在此模式中找到的是实施析构函数,因为每个实例都包含实例的向量,所以如果我删除一个实例,我也删除包含所有其他实例的向量。
是否有可能使这项工作?或者它只是一个错误的模式,简单而简单?
一个单身人士应该是关于对象生命而不是阶级设计。 – Simple
在我看来,你只是想跟踪有史以来创建的这个类的每个实例...没有什么错。它用在一些流行的框架中(例如用于窗口)。在析构函数中,只需从列表中删除它自己。顺便说一下,不要使用矢量,使用地图,以便更快地找到它。你可能想用一个互斥体来包装它,以防在不同的线程中创建和销毁实例。你在这里得到的是一个窗口类(MFC,QT,WxWidget等,它们都使用相同的窗口模式)。 – thang