单线程
class Singleton {
private Singleton() {};
private static Singleton instance = null;
public static Singleton createInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class HelloWorldjava {
public static void main(String[] args) {
Singleton s1 = Singleton.createInstance();
Singleton s2 = Singleton.createInstance();
if (s1 == s2) {
System.out.println("只有一个实例被创建!");
}
}
}
预先加载
class Singleton {
private Singleton() {};
private static Singleton instance = new Singleton();
public static Singleton createInstance() {
return instance;
}
}
public class HelloWorldjava {
public static void main(String[] args) {
Singleton s1 = Singleton.createInstance();
Singleton s2 = Singleton.createInstance();
if (s1 == s2) {
System.out.println("只有一个实例被创建!");
}
}
}
按需创建
class Singleton {
private Singleton() {};
private static class Helper {
static Singleton instance = new Singleton();
}
public static Singleton createInstance() {
return Helper.instance;
}
}
public class HelloWorldjava {
public static void main(String[] args) {
Singleton s1 = Singleton.createInstance();
Singleton s2 = Singleton.createInstance();
if (s1 == s2) {
System.out.println("只有一个实例被创建!");
}
}
}