单例模式在 Runtime 类中的应用

JDK 中 java.lang.Runtime 类是一个单例类

每个 Java 应用在运行时会启动一个 JVM 进程,每个 JVM 进程都只对应一个 Runtime 实例,用于查看 JVM 状态以及控制 JVM 行为。进程内唯一,所以比较适合设计为单例。在编程的时候,我们不能自己去实例化一个 Runtime 对象,只能通过 getRuntime() 静态方法来获得。

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

  public static Runtime getRuntime() {
    return currentRuntime;
  }
  
  /** Don't let anyone else instantiate this class */
  private Runtime() {}
  
  //....
  public void addShutdownHook(Thread hook) {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
       sm.checkPermission(new RuntimePermission("shutdownHooks"));
    }
    ApplicationShutdownHooks.add(hook);
  }
  //...
}

其他模式在 JDK 中的应用汇总

模板模式(扩展性和复用性): Java Servlet、JUnit TestCase、Java InputStream、Java AbstractList

享元模式:Integer 类中的 -128~127 之间的整型对象是可以复用的, String 类型中的常量字符串也是可以复用的

职责链模式:Java Servlet 中的 Filter 是通过职责链来实现的。拦截器、过滤器这些功能绝大部分都是采用职责链模式来实现的

posted @ 2022-10-20 18:08  请务必优秀  阅读(71)  评论(0编辑  收藏  举报