none
restricting creation of object ????? RRS feed

  • Question

  • Hi,
       how can i restrict creation of objects of a class upto five objects only ?

    Thanx in advance
    Friday, May 9, 2008 11:21 AM

Answers

  • Hi,

     

    Some logical steps to achieve your requirement:

     

    1. Create a class and make its constructor private.

    2. Create a static variable that keeps a track of the count of the instances created

    3. Create a method that creates the instance and returns the instance. Before creating and returning the instance, check for the count of instances.

     

    Something like this:

     

    Code Snippet

    public class LimitedInstances
    {
     
     private LimitedInstances()
     {
     }

    private static int instanceCnt;
     
     public static LimitedInstances CreateInstances()
     {
       if(instanceCnt < 5)
       {
         instanceCnt++;
         return new LimitedInstances();
       }

       else

       {

         return  null;

       }
    }
    }

     

     

     

    HTH,
    Suprotim Agarwal

     

    Friday, May 9, 2008 11:33 AM
    Moderator

All replies

  • Hi,

     

    Some logical steps to achieve your requirement:

     

    1. Create a class and make its constructor private.

    2. Create a static variable that keeps a track of the count of the instances created

    3. Create a method that creates the instance and returns the instance. Before creating and returning the instance, check for the count of instances.

     

    Something like this:

     

    Code Snippet

    public class LimitedInstances
    {
     
     private LimitedInstances()
     {
     }

    private static int instanceCnt;
     
     public static LimitedInstances CreateInstances()
     {
       if(instanceCnt < 5)
       {
         instanceCnt++;
         return new LimitedInstances();
       }

       else

       {

         return  null;

       }
    }
    }

     

     

     

    HTH,
    Suprotim Agarwal

     

    Friday, May 9, 2008 11:33 AM
    Moderator
  • Hello!
    Just one tiny correction: public LimitedInstances CreateInstances() should be static ; don't you agree?

    J.C.
    Friday, May 9, 2008 3:03 PM
  • Hi,

     

    rdc02271 thanks for pointing out that Smile I have added static to the method.

     

    HTH,

    Suprotim Agarwal

     

    Friday, May 9, 2008 6:54 PM
    Moderator