寻找jdk中的设计模式之单例模式

本文介绍了单例模式的概念,强调了在类加载时不应立即创建对象以优化性能。讨论了单例模式的应用场景和多线程环境下的注意事项。详细阐述了Java源码中Runtime类如何运用单例模式,并提到了Spring MVC中Controller的单例设计。最后推荐了相关参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、概念

一个类只有一个对象。

注意:
对于单例模式,我们需要注意并不一定要在类加载的时候就产生对象,这样会影响性能。比如单例模式的实现中的饿汉模式,此模式中单例在类加载之时就产生了,可是万一这个对象需要消耗很多资源呢?所以建议在需要创建时,才创建对象。

二、应用场景

当一个类只需要存在它的一个对象时,可以选择。

对于单例,需要注意两点

  1. 什么时候对对象进行初始化(类加载时/真正需要对象时)
  2. 线程问题。多线程环境下也要保证只有一个类的实例。
  3. 加锁会影响性能。如果每次获取对象,都有一个加锁操作,会非常影响性能。其实只有在第一次创建单例对象时才需要加锁,以后获取单例对象时就不需要加锁了。

三、java源码中单例模式的应用

说道单例模式,自然就想到了它的最简单的两种实现——懒汉模式、饿汉模式。然而,单例模式还有其他实现,如双重锁定检查、volatile。为了避免重复造轮子,请参考 单例模式、双检测锁定DCL、volatile详解

在jdk中应用,java.lang.Runtime就利用了单例模式。
在这里插入图片描述

/**
 * Every Java application has a single instance of class
 * <code>Runtime</code> that allows the application to interface with
 * the environment in which the application is running. The current
 * runtime can be obtained from the <code>getRuntime</code> method.
 * <p>
 * An application cannot create its own instance of this class.
 *
 * @author  unascribed
 * @see     java.lang.Runtime#getRuntime()
 * @since   JDK1.0
 */

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() {}
}

正如注释所说,每一个java应用程序都有一个Runtime实例。Runtime的单例模式是采用饿汉模式创建的,意思是当你加载这个类文件时,这个实例就已经存在了。

Runtime类可以取得JVM系统信息,或者使用gc()方法释放掉垃圾空间,还可以使用此类运行本机的程序。具体参考 Java常用类库——Runtime类

spring Mvc 中的controller 默认是单例模式的,解析
spring mvc Controller单例解析

四、参考文献

单例模式、双检测锁定DCL、volatile详解
Double-checked Locking (DCL) and how to fix it (ctd)
Java常用类库——Runtime类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值