转载:https://mp.weixin.qq.com/s/T2wav9ewkSmXxB4VYqSWBg
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){
}
public static Singleton getInstance() {
return instance;
}
}
public class Sintelon {
private static Sintelon instance = new Sintelon();
public static String VARIABLE = "hello world!";
private Sintelon() {
System.out.println("Singtelon is created!");
}
public static Sintelon getInstance() {
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(Sintelon.VARIABLE);
}
}
}
public class LazySintelon {
private static LazySintelon instance;
public static String VARIABLE = "hello world!";
private LazySintelon() {
System.out.println("LazySintelon is created!");
}
public static synchronized LazySintelon getInstance() {
if (instance == null) {
instance = new LazySintelon();
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(LazySintelon.VARIABLE);
}
}
}
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
public class Singleton {
private static class SingletonHolder {
private static final Singleton instance= new Singleton();
}
private Singleton (){
}
public static final Singleton getInstance() {
return SingletonHolder.instance;
}
}