package designMode.Singleton;
public class Singleton_template {
private String id;
private String information;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
@Override
public String toString() {
return "Singleton_template{" +
"id='" + id + '\'' +
", information='" + information + '\'' +
'}';
}
/**
* 枚举类实现单例模式
* 枚举类型是线程安全的,并且只会装载一次,枚举类型是所用单例实现中唯一一种不会被破坏的单例实现 模式
*/
private Singleton_template() {
}
private enum Singleton {
Singleton_template;
private final Singleton_template instance;
Singleton() {
instance = new Singleton_template();
}
private Singleton_template getInstance() {
return instance;
}
}
public static Singleton_template getInstance() {
return Singleton.Singleton_template.getInstance();
}
}
public class Singleton_templateDemo {
public static void main(String[] args) {
Singleton_template instance = Singleton_template.getInstance();
instance.setId("1");
instance.setInformation("枚举类实现单例模式,枚举类型是线程安全的,并且只会装载一次");
System.out.println(instance);
}
} |