- 懒汉式: 懒汉式单例类.在第一次调用的时候实例化自己
public class Singleton {
private static Singleton mInstance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (null == mInstance) {
mInstance = new Singleton();
}
return mInstance;
}
}
- 恶汉式:饿汉式单例类.在类初始化时,已经自行实例化
public class Singleton {
private static Singleton mInstance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return mInstance;
}
}
public class Singleton {
private static Singleton mInstance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (null == mInstance) {
mInstance = new Singleton();
}
return mInstance;
}
}
public class Singleton {
private static Singleton mInstance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (null == mInstance) {
synchronized (Singleton.class) {
if (null == mInstance) {
mInstance = new Singleton();
}
}
}
return mInstance;
}
}
public class Singleton {
public static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
}
public static final Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}