Forums Register Login
Limited no of Objects
Hi Ranchers ! Can we restrict someone to create a limited objects of a class ?
Yes you can. You can create a private constructor for your class and you can create a static factory method which creates an instance of your object. In this method you can increment a counter, and throw an exception/return null, when the limit is exceeded.
use singleton pattern, there you maintain a global counter, which tracks the number of objects created and keeps a reference of them. Oncecounter exceeds, you do not allow to create any further object of your class.
sorry my mistake...
yes you can. Give the responsibility of creating the object of the class, to the class itself (which takes care how many objects have been created) by making its constructor private and creating one public static method which creates the object of the class and returns to the client.

Agree. That is a variant of the singleton pattern.

sujith Acharya wrote:

Minor note: the above code is not thread save. So in case you're accessing getObject from multiple threads (which usually happens when used within a webapplication) you'll need to add the synchronized keyword:

Else you'll might get more objects than wanted, if getObject gets executed at exactly the same time.
Do the next thing next. That’s a pretty good rule. Read the tiny ad, that’s a pretty good rule, too.
global solutions you can do in your home or backyard

This thread has been viewed 1123 times.

All times above are in ranch (not your local) time.
The current ranch time is
Apr 19, 2019 20:14:03.