单例模式之枚举

本文介绍了如何利用枚举来实现单例模式,这种方法在多线程环境下安全且防止反序列化创建新对象。同时,文章提到了JDK源码中的RUNTIME对象就是运用了饿汉式的静态变量实现的单例模式,并强调了单例模式在节省系统资源和提高性能方面的优势,以及适用的场景,如工具类、频繁创建销毁的对象等。

利用枚举实现单例模式

enum Singleton8{
    INSTANCE;
    public void sayOk(){
        System.out.println("ok~");
    }
}

借助jdk1.5新加的枚举,可以避免多线程问题,还可以防止反序列化重新创建新的对象。可以使用此种方法。

单例模式在JDK源码中的体现

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}

在JDK中的RUNTIME对象就是利用了单例模式中的饿汉式的静态变量的方式实现的。

单例模式的注意事项和细节说明

  • 单例模式保证了系统内存中只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能。
  • 当想实例化一个单例对象的时候,必须要记住使用相应的获取对象的方法,比如对象的getInstance()方法,而不是使用new
  • 单例模式的使用场景:需要频繁的创建和销毁的对象,创建对象会消耗过多的时间和资源(重量级对象),但又经常用到的对象,工具类对象,频繁访问数据库或文件的对象(比如数据源,session工厂等)
单例模式枚举实现线程池可利用枚举天然的单例特性。由于每个枚举项都是`public static final`的,所以枚举天然就是单例的,且枚举类型不能被继承,也不能有显式的构造函数,适合用于实现单例模式。以下为示例代码: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; // 定义一个枚举类型来实现单例线程池 enum ThreadPoolSingleton { // 枚举项,代表单例实例 INSTANCE; // 线程池对象 private final ExecutorService threadPool; // 枚举的构造函数,用于初始化线程池 ThreadPoolSingleton() { // 创建一个固定大小的线程池,这里设置为 10 个线程 threadPool = Executors.newFixedThreadPool(10); } // 获取线程池的方法 public ExecutorService getThreadPool() { return threadPool; } } // 测试类 public class Main { public static void main(String[] args) { // 获取单例线程池实例 ExecutorService pool = ThreadPoolSingleton.INSTANCE.getThreadPool(); // 向线程池提交任务 pool.submit(() -> { System.out.println("Task is running on thread: " + Thread.currentThread().getName()); }); // 关闭线程池 pool.shutdown(); } } ``` 在上述代码中,`ThreadPoolSingleton`是一个枚举类型,其中的`INSTANCE`是枚举项,代表单例实例。在枚举的构造函数中,使用`Executors.newFixedThreadPool(10)`创建了一个固定大小为 10 的线程池。`getThreadPool`方法用于获取这个线程池实例。在`Main`类的`main`方法中,通过`ThreadPoolSingleton.INSTANCE.getThreadPool()`获取线程池实例,并向其提交了一个任务,最后关闭了线程池。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值