• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Understanding singleton pattern

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Trying to fully understand the singleton pattern where you only want one instance of a class to exist (i.e. a database connection pool). Static methods exists at the class level and should be independent of instance state. The getInstance() method returns an instance of the singleton class. This instance is declared as static which means it will only ever exist once for this class - thus all objects calling this static method will be getting the same one instance. Am I understanding this correctly? What is preventing other objects from importing this class and creating a new instance of it?
Singleton singleClass = new Singleton();
You would want to force other classes to use the getInstance() method wouldn't you?

Thanks for your help in understanding this.
- - John
 
John Fairbairn
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK... figured out answer to one of my questions of why you can't do Singleton single = new Singleton()..
Noticed the private constructor:

Please let me know how you understand the singleton works.
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You may want to take a look at the JavaWorld article "When is a singleton not a singleton?".
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic