I've been Googling for about an hour now and I still don't have a clear idea of what a singleton is. Can anyone make it a bit clearer to me and perhaps post a code example?
All I know is that you can only have one instance of a given class. But can't you just then use a static class for that?
Thanks in advance!
The simple plain English1 version is: Singleton Class is a Class that has, and can only have, only one instance.
But can't you just then use a static class for that?
No. That's not what a "static" class is in Java. In Java "static" classes can have multiple instances just like any other class.
The static
keyword is used (for classes) to mean that the instance of a nested class is not tied to a specific instance of the enclosing class. And that means that expressions in the nested class cannot refer to instance variables declared in the enclosing class.
Prior to Java 1.5 (aka Java 5), there was no support for the singleton design pattern in Java. You just implemented them in plain Java; e.g.
/** There is only one singer and he knows only one song */
public class Singer {
private static Singer theSinger = new Singer();
private String song = "I'm just a singer";
private Singer() {
/* to prevent instantiation */
}
public static Singer getSinger() {
return theSinger;
}
public String getSong() {
return song;
}
}
Java 1.5 introduced the enum
types which can be used to implement singletons, etc.
/** There are two Singers ... no more and no less */
public enum Singer {
DUANE("This is my song"),
RUPERT("I am a singing bear");
private String song;
Singer(String song) {
this.song = song;
}
public String getSong() {
return song;
}
}
1 - Of course, you need to understand what "class" and "instance" mean. Since the Programming / IT English meanings of these words is different to the "plain English" meanings, it is a stretch to call this a "plain English" description. On the other hand, if the reader doesn't already understand what "class" and "instance" mean, they don't have the base knowledge needed to understand the "singleton" idea, or see the point of it.