auto commit
This commit is contained in:
parent
8674be4460
commit
941f8e352c
|
@ -177,44 +177,46 @@ public class Singleton {
|
|||
|
||||
#### Ⅵ 枚举实现
|
||||
|
||||
使用单元素的枚举类型来实现单例模式,相对于常规的单例模式,枚举实现的单例天生具有防止反射实例化对象和反序列化产生实例化对象,而且代码更加简洁,非常适合单例模式场景下使用。以下是枚举单例模式的实现。
|
||||
```java
|
||||
public enum Singleton {
|
||||
|
||||
```java
|
||||
|
||||
public enum EnumSingleton {
|
||||
INSTANCE; //单元素枚举实现单例
|
||||
INSTANCE;
|
||||
|
||||
private String objName;
|
||||
|
||||
|
||||
public String getObjName() {
|
||||
return objName;
|
||||
}
|
||||
|
||||
|
||||
public void setObjName(String objName) {
|
||||
this.objName = objName;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// 单例测试
|
||||
EnumSingleton firstSingleton = EnumSingleton.INSTANCE;
|
||||
Singleton firstSingleton = Singleton.INSTANCE;
|
||||
firstSingleton.setObjName("firstName");
|
||||
System.out.println(firstSingleton.getObjName());
|
||||
|
||||
EnumSingleton secondSingleton = EnumSingleton.INSTANCE;
|
||||
Singleton secondSingleton = Singleton.INSTANCE;
|
||||
secondSingleton.setObjName("secondName");
|
||||
System.out.println(firstSingleton.getObjName());
|
||||
System.out.println(secondSingleton.getObjName());
|
||||
|
||||
// 反射获取实例测试
|
||||
try {
|
||||
EnumSingleton[] enumConstants = EnumSingleton.class.getEnumConstants();
|
||||
for (EnumSingleton enumConstant : enumConstants) {
|
||||
Singleton[] enumConstants = Singleton.class.getEnumConstants();
|
||||
for (Singleton enumConstant : enumConstants) {
|
||||
System.out.println(enumConstant.getObjName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
该实现在多次序列化再进行反序列化之后,不会得到多个实例。而其它实现,为了保证不会出现反序列化之后出现多个实例,需要使用 transient 修饰所有字段,并且实现序列化和反序列化的方法。
|
||||
|
|
Loading…
Reference in New Issue
Block a user