一.常量方式类加载时创建实例
public class Singleton {
//定义一个唯一实例
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
//获取实例
public static Singleton getInstance(){
return INSTANCE;
}
}
二.第一次调用时通过内部类创建实例
public class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
三.第一次使用时创建实例
public class Singleton {
//定义静态的变量
private static Singleton singleton;
private Singleton() {}
//获取对象
public static Singleton getInstance() {
//检查是否被创建
if (singleton == null) {
synchronized (Singleton.class) {
//再次进行检查
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
四.使用enum创建单例,和第二种方式类似; 在第一次调用时初始化
public enum Singleton {
instance;
private Singleton() {}
}