使用的場景:在系統中本質上是唯一的,只要一個實例對象
jdk1.5之前的實現方式
/**
* 單例的實現方式1
*/
public class SingLeton {
// 靜態final域
public static final SingLeton INSTANCE = new SingLeton();
// 私有
private SingLeton() {
}
}
變成可序列化public class SingLeton implements Serializable {
// 靜態final域
public static final SingLeton INSTANCE = new SingLeton();
// 私有
private SingLeton() {
}
// 保證singleton屬性,加readResolve,並且實力域要用transient修飾
public Object readResolve() {
return INSTANCE;
}
}
/**
*單例的實現方式2
*/
public class SingLeton2 {
// 私有
public static final SingLeton2 INSTANCE = new SingLeton2();
// 私有
private SingLeton2() {
}
// 靜態工廠方法
public static SingLeton2 getInstance() {
return INSTANCE;
}
}
變成可序列化public class SingLeton2 implements Serializable {
// 私有
private static final SingLeton2 INSTANCE = new SingLeton2();
// 私有
private SingLeton2() {
}
// 靜態工廠方法
public static SingLeton2 getInstance() {
return INSTANCE;
}
// 保證singleton屬性,加readResolve,並且實力域要用transient修飾
public Object readResolve() {
return INSTANCE;
}
}
jdk1.5之後的實現方式
/**
* 方法3:枚舉(單元素的枚舉是singleton最佳實踐,無償提供序列化機制,絕對防止多次實例化)
*/
public enum SingLeton3 {
INSTANCE;
}