java枚举类单例示例

public class Singleton {
    //私有化构造函数
    private Singleton(){ }
 
    //定义一个静态枚举类
    static enum SingletonEnum{
        //创建一个枚举对象,该对象先天为单例
        INSTANCE;
        private Singleton singletion;
        //私有化枚举的构造函数
        private SingletonEnum(){
            singletion=new Singleton();
        }
        public Singleton getInstnce(){
            return singletion;
        }
    }
 
    //对外撮合一个获取Singleton对象的静态方法
    public static Singleton getInstance(){
        return SingletonEnum.INSTANCE.getInstnce();
    }
    public static void main(String[] args) {
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance()==Singleton.getInstance());
    }

}

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0