枚举单例有序列化和线程安全的保证, 而且也是最简单的。 同时枚举类也就是一个普通的Java类一样。
package cn.stu;
public enum Person {
instance("小强");
private final String name;
private Person(String name){
this.name = name;
}
public String getVal(){
return this.name;
}
}
package cn.stu;
public class Main {
public static void main(String[] args) {
Person person_A = Person.instance;
Person person_B = Person.instance;
System.out.println(person_A.getVal());
System.out.println(person_A == person_B);
}
}
转载请注明原文地址: https://ju.6miu.com/read-700147.html