Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to get the Single Instance of a class - singleton -Basic

 
kalpana Kumar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I have a basic question as to how to obtain a single instance of a class other than using Singleton Pattern.

I really appreciate any suggestion.

Thanks
 
Logan Owen
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean create a new instance? Because that would be:



Or whatever the constructor is.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A singleton pattern limits the number of instances that can be created for a particular class. So -- by definition -- whatever code you use to achieve this is a "singleton pattern."

In general, the constructor is made private, and then a static method keeps track of how many instances have been created, and returns a new instance if appropriate.

There are variations on how to implement this. For example, if the singleton is actually meant to limit the number instances to one, then it could be as simple as making the constructor private, declaring a private static instance of the class as a member, then using a public static method to return a reference to that static instance.



Other approaches get more complex -- using counters to track the number of instances, or cleverly employing "this" and "null." Try searching the boards (or the net) for "singleton."
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the OO, Patterns, UML and Refactoring forum...
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:
A singleton pattern limits the number of instances that can be created for a particular class. So -- by definition -- whatever code you use to achieve this is a "singleton pattern."


The global access point (the getInstance() method) also is inherent to the Singleton pattern.

An alternative is discussed at http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The GoF book has a section on subclassing and accessing singletons, talks about factories, registries and such. Then the class itself doesnt guarantee that only a single instance is every made and doesn't provide the single point of access. Other objects do that for it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic