枚举类实现单例模式

  • 主类
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);
   }
}
发布了45 篇原创文章 · 获赞 0 · 访问量 1910

猜你喜欢

转载自blog.csdn.net/weixin_41804367/article/details/101618990