The simple plain English1 version is: Singleton Class is a Class that has, and can only have, only one instance.
但是你不能为此使用静态类吗?
不,这不是 Java 中的“静态”类。在 Java 中,“静态”类可以像任何其他类一样拥有多个实例。
The static
使用关键字(对于类)意味着嵌套类的实例不依赖于封闭类的特定实例。这意味着嵌套类中的表达式不能引用封闭类中声明的实例变量。
在 Java 1.5(又名 Java 5)之前,Java 中不支持单例设计模式。您只是用纯 Java 实现了它们;例如
/** 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 引入了enum
可用于实现单例等的类型。
/** 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.