饿汉模式:在类加载时就完成了初始化,所以类加载比较慢,但获取对象的速度快。
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
懒汉模式:在类加载时不初始化,等到第一次被使用时才初始化。
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}