java面经:枚举实现单例

//单例类
public class Singleton {
    // 实例变量
    private byte[] data = new byte[1024];
    //构造器私有
    private Singleton() {
        System.out.println("+++++");
    }
 
   // 使用枚举充当 holder
    //枚举类
    private enum EnumHolder{
        INSTANCE;
        private Singleton instance;
 
       EnumHolder(){
           this.instance = new Singleton();
       }
 
       private Singleton getSingleton(){
           return instance;
       }
   }
    //静态方法获取枚举中的实例
    public static Singleton getInstance() {
        return EnumHolder.INSTANCE.getSingleton();
    }
 
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
    }
}

posted @ 2022-07-24 14:21  无极是一种信仰  阅读(201)  评论(0)    收藏  举报