Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Limited no of Objects

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers ! Can we restrict someone to create a limited objects of a class ?
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry my mistake...
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Marshal
Posts: 69871
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree. That is a variant of the singleton pattern.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 don't always make ads but when I do they're tiny
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic