How to make class to allow creation of 3 objects only

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.



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.

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

Need Your Help

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.