jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Understanding singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Understanding singleton pattern" Watch "Understanding singleton pattern" New topic

Understanding singleton pattern

John Fairbairn
Ranch Hand

Joined: May 30, 2002
Posts: 55
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

Joined: May 30, 2002
Posts: 55
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.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
You may want to take a look at the JavaWorld article "When is a singleton not a singleton?".

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link: http://aspose.com/file-tools
subject: Understanding singleton pattern
jQuery in Action, 3rd edition