Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does Singleton has many definition?

 
alex han
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is Singleton's original definition?
in developerworks is:
public class Singleton {
private static Singleton s;
private Singleton(){};
/**
* Class method to access the singleton instance of the class.
*/
public static Singleton getInstance() {
if (s == null)
s = new Singleton();
return s;
}
}
and in other is:
public class Singleton {
  private Singleton(){}

  private static Singleton instance = new Singleton();
  public static Singleton getInstance() {
    return instance;   
   }
}
or:
public class Singleton {
  private static Singleton instance = null;
  public static synchronized Singleton getInstance() {
 
  if (instance==null)
    instance=new Singleton();
  return instance;   }
}
now i want to know how many definition about Singleton?which is most used?
thanks a lot
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The definition of Singleton is: a class ensuring that there is only one instance of it and providing a global point of access to it by a class method.
What you presented are just the two most typical implementations.
The one assigning the instance at the field declaration has the advantage that it is inherently thread-safe.
The other, using lazy initialization, needs some amount of explicite synchronization, but defers the creation of the instance until you really need it for the first time.
Did that help?
PS: Singleton is one of the simplest design patterns, but also one of the easiest to be misused. Be *very* wary at applying it!
See also http://c2.com/cgi/wiki?SingletonPattern
 
alex han
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes thank you very much
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome!
BTW, just in the case that "hit demo" isn't your real name - could you please adjust your display name so that it conforms to our naming policy? Thank you very much!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic