public class A {
public static A getInstance() {
return InstanceHolder.instance;
}
private static class InstanceHolder {
public static A instance = new A();
}
}
懒汉,线程不安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉,线程安全
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}