第一种形式:饿汉式单例
public class Singleton {
private Singleton(){}
private static Singleton instance = new 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=newSingleton();
return instance;
}
}
区别:
<strong>“懒汉式”是在你真正用到的时候才去建这个单例对象,线程安全</strong>
<strong>“饿汉式”是在不管你用的用不上,一开始就建立这个单例对象:比如:有个单例对象,线程不安全</strong>