枚举方式单例

x33g5p2x  于2022-04-13 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(218)

一 点睛

使用枚举方式实现单例是很多优秀的开源代码中经常使用的方式,枚举类型不允许被继承,同样是线程安全且只能被实例化一次,但是枚举类型不能够懒加载,对 Singleton 主动使用,比如调用其中的静态方法则 INSTANCE 会立即得到实例化。

二 代码

package singleton.singleton4;

public enum Singleton {
    INSTANCE;
    // 实例变量
    private byte[] data = new byte[1024];
    private static Singleton instance = null;

    Singleton() {
        System.out.println("INSTANCE will be initialized immediately");
    }

    public static void method() {
        System.out.println("调用该方法主动使用单例");
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) {
        Singleton.method();

        new Thread(()->{
            Singleton instance = Singleton.getInstance();
            System.out.println(instance);
        }).start();

        new Thread(()->{
            Singleton instance = Singleton.getInstance();
            System.out.println(instance);
        }).start();
    }
}

三 测试

INSTANCE will be initialized immediately

调用该方法主动使用单例

INSTANCE

INSTANCE

四 扩展

可对该代码实现懒加载特性,类似于 Holder 的方式,改进后的代码如下。

1 代码

package singleton.singleton5;

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);
    }
}

2 测试结果

+++++

singleton.singleton5.Singleton@7a81197d

相关文章

微信公众号

最新文章

更多