单例模式在JDK 应用
- ctrl + n,搜索Runtime
public class Runtime { private static final Runtime currentRuntime = new Runtime(); private static Version version; /** * Returns the runtime object associated with the current Java application. * Most of the methods of class {@code Runtime} are instance * methods and must be invoked with respect to the current runtime object. * * @return the {@code Runtime} object associated with the current * Java application. */ public static Runtime getRuntime() { return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {} /** * Terminates the currently running Java virtual machine by initiating its * shutdown sequence. This method never returns normally. The argument * serves as a status code; by convention, a nonzero status code indicates * abnormal termination. * * <p> All registered {@linkplain #addShutdownHook shutdown hooks}, if any, * are started in some unspecified order and allowed to run concurrently * until they finish. Once this is done the virtual machine * {@linkplain #halt halts}. * * <p> If this method is invoked after all shutdown hooks have already * been run and the status is nonzero then this method halts the * virtual machine with the given status code. Otherwise, this method * blocks indefinitely. * * <p> The {@link System#exit(int) System.exit} method is the * conventional and convenient means of invoking this method. * * @param status * Termination status. By convention, a nonzero status code * indicates abnormal termination. * * @throws SecurityException * If a security manager is present and its * {@link SecurityManager#checkExit checkExit} method does not permit * exiting with the specified status * * @see java.lang.SecurityException * @see java.lang.SecurityManager#checkExit(int) * @see #addShutdownHook * @see #removeShutdownHook * @see #halt(int) */ public void exit(int status) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkExit(status); } Shutdown.exit(status); }
- 注意事项和细节
1) 单例模式保证了 系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能 2) 当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用new 3) 单例模式使用的场景:需要频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级对象),但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象(比如数据源、session工厂等)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术