一、簡介
Java中單例模式定義:“一個類有且僅有一個實例,并且自行實例化向整個系統提供”。要點就是只能有一個實例,且可以向整個系統提供該實例。一般來說有這五種寫法:懶漢式,餓漢式,雙重鎖形式,靜態內部類,枚舉。
二、實例
2.1懶漢式
<code>
public class Singleton{
private static Singleton instance = null;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
</code>
特點:延遲加載,但同步了整個方法,效率低,不推薦使用。
2.2 餓漢式
<code>
public class Singleton{
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
</code>
特點:代碼簡潔,但是沒有延遲加載。
2.3 雙重鎖形式
<code>
public class Singleton{
private volatile static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
</code>
特點:延遲加載,使用了volatile。
2.4 靜態內部類
<code>
public class Singleton{
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
</code>
特點:延遲加載
2.5 枚舉
<code>
public enum Singleton{
INSTACNE;
}
</code>
特點:可防止反序列化重新創建新的對象