枚举方式单例

一 点睛

使用枚举方式实现单例是很多优秀的开源代码中经常使用的方式,枚举类型不允许被继承,同样是线程安全且只能被实例化一次,但是枚举类型不能够懒加载,对 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值