aspose file tools*
The moose likes Beginning Java and the fly likes Limited no of Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Limited no of Objects" Watch "Limited no of Objects" New topic
Author

Limited no of Objects

faisal hameed
Ranch Hand

Joined: Jan 19, 2009
Posts: 48
Hi Ranchers ! Can we restrict someone to create a limited objects of a class ?


Regards, M Faisal Hameed
PUCIT, Pakistan
Miklos Szeles
Ranch Hand

Joined: Oct 21, 2008
Posts: 142
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.
Rahul P Kumar
Ranch Hand

Joined: Sep 26, 2009
Posts: 188
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.
leroy tsruya
Ranch Hand

Joined: Sep 24, 2009
Posts: 57
sorry my mistake...
sujith Acharya
Ranch Hand

Joined: Dec 25, 2006
Posts: 60
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.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Agree. That is a variant of the singleton pattern.
Gerbrand van Dieijen
Ranch Hand

Joined: Nov 28, 2008
Posts: 30
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Limited no of Objects