Restrict the number of object instantiations from a class to a given number

前端 未结 2 1580
有刺的猬
有刺的猬 2021-01-07 06:02

Given a class, I would like to limit the number of objects created from this class to a given number, say 4.

Is there a method to achieve this?

2条回答
  •  离开以前
    2021-01-07 06:42

    You're looking for the instance manager pattern. Basically what you do is restrict instantiations of that class to a manager class.

    class A
    {
    private: //redundant
       friend class AManager;
       A();
    };
    
    class AManager
    {
       static int noInstances; //initialize to 0
    public:
       A* createA()
       {
          if ( noInstances < 4 )
          {
             ++noInstances;
             return new A;
          }
          return NULL; //or throw exception
       }
    };
    

    A shorter way is throwing an exception from the constructor, but that can be hard to get right:

    class A
    {
    public:
       A()
       {
           static int count = 0;
           ++count;
           if ( count >= 4 )
           {
               throw TooManyInstances();
           }
       }
    };
    

提交回复
热议问题