2

i was asked this question in my interview that how to make a class that can only allows 3 objects creation.

i suggested to take a static variable and a static function for creation of object and while returning reference of new object just check value in static variable to check count of no. of object already created.

second approach i told him to take 3 static object of same class in that class only and let the user use those object only.

please tell me the best approach to perform above operation.

Thanks

Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178

8 Answers8

3

I think your first approach is closer to the question: make private constructor and a static newInstance() method that checks how many instances were created before and returns null if it's more than 3.

Second approach is also ok, though.

EDIT @Saurabh: even though the question says nothing about what to do in case the object is gc-ed, let's develop this:

  1. A dirty hack to the first solution: override finalize() method that decrements the static counter of objects.
  2. A pool of objects with some sort of a locking mechanism that only allows three, let's say, users, use the objects ate the same time.
Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68
3

In Java, the simplest solution would be to use an enum.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
2

Step one would be to write your own VM. Reflection could be used to circumvent most of the answers here, a customised classloader would defeat them all. Moral of the story: sufficiently privileged code can do whatever it wants to your classes.

CurtainDog
  • 3,175
  • 21
  • 17
  • +1 : for Reflection bit , i were aware of what you are talking about , simpley whole Singleton Pattern can be broken with reflection and i know that but sometime you just need to answer what is asked. – TalentTuner Dec 01 '10 at 08:54
1

my implementation is would be as below , it is not perfect but my thoughts at initial

 public class ThreeInstances
{

    private static int TOTALINSTANCECOUNT = 0;

    private ThreeInstances()
    {
    }

     private object objLock = new object();

     private static List<ThreeInstances> objThreeInstances = new List<ThreeInstances>();

     public static ThreeInstances GetInstance()
     {

         if (TOTALINSTANCECOUNT < 3)
         {
             lock (objLock)
             {
                 objThreeInstances.Add(new ThreeInstances());
                 Interlocked.Increment(ref TOTALINSTANCECOUNT);
                 return objThreeInstances[TOTALINSTANCECOUNT];

             }

         }
         else
         {
             Random r = new Random(0);
          int value =    r.Next(2);
          return objThreeInstances[value];
         }


     }

     ~ThreeInstances()
     {
         Interlocked.Decrement(ref TOTALINSTANCECOUNT);

         if (TOTALINSTANCECOUNT < 3)
         {
             lock (objLock)
             {
                 objThreeInstances.Add(new ThreeInstances());
                 Interlocked.Increment(ref TOTALINSTANCECOUNT);
                 return objThreeInstances[TOTALINSTANCECOUNT];

             }

         }
     }
}
TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0
public class Threeobject
{
    public static int objectcount { get; set; }

    public Threeobject()
    {
        if (Threeobject.objectcount >= 3)
        {
            throw new Exception("You cannot create more then three object");
        }
        Threeobject.objectcount++;
    }
}
0

Singleton design pattern with some modifications two support three instances instead of one.

sherbeny
  • 11
  • 3
0

Something like this... simple Singleton Pattern... You can add direct access for the three instances via Getters.

import java.util.ArrayList;
import java.util.Collections;

public class ThreeInstanceClazz {

    private static ArrayList<ThreeInstanceClazz> instances= null;

    private ThreeInstanceClazz(){
        // Only a private constructor!!
    }

    public static ThreeInstanceClazz getInstance(){
        if(instances == null){
            instances = new ArrayList<ThreeInstanceClazz>(3);
        }

        if(instances.size() < 3){
            ThreeInstanceClazz newOne = new ThreeInstanceClazz();
            instances.add(new ThreeInstanceClazz());

            // return newly created
            return newOne;
        }else{
            // return random instance ... or anything else
            Collections.shuffle(instances);
            return instances.get(0);
        }
    }
}
Gruber
  • 531
  • 1
  • 6
  • 17
0

Check out Noldorin's answer in this thread. May this would be helpful.

Community
  • 1
  • 1
VJOY
  • 3,752
  • 12
  • 57
  • 90