如何限制类的实例数量? [英] How can I limit the number of instances of a class?
问题描述
作为一个练习,我希望创建一个不能有多于N个实例的类。我该如何做?
As an exercise, I wish to make a class that can't have more than N instances. How can I do that?
例如,假设您想要限制连接到数据库的数量,以使不超过N个用户可以同时连接。我了解如何创建单身:
Suppose, for example, you want to limit number of connection to database so that no more than N users can connect at the same time. I understand how to make a singleton:
class Singleton {
private:
Singleton(const Singleton&);
Singleton();
public :
static Singleton Instance() {
static Singleton p;
if(!p) {
p = new Singleton;
}
};
但是如果有N> 1个对象,我需要帮助。
But if there N > 1 objects, I need help.
推荐答案
首先,为什么?
的方式,你已经知道如何做一个类,只允许一个实例,我假设?通常,你使用静态实例和私有构造函数(或其一些变体)。要将其推广到N个实例,您只需存储一个静态数组。
Once we get that question out of the way, you already know how to make a class that allows for just one instance, I assume? Usually, you do that with a static instance and a private constructor (or some variation thereof). To generalise that to N instances, all you need to do is store a static array of instances.
最后, ?
Finally, seriously, WHY?
这篇关于如何限制类的实例数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!