java API中的单例类 [英] singleton class in java API

查看:75
本文介绍了java API中的单例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java API中的Singleton Pattern的最佳例子是什么? Runtime类是单例吗?

What are the best examples of Singleton Pattern in Java API? Is Runtime class a singleton?

推荐答案

只有两个例子可以想到:

Only two examples comes to mind:

  • java.lang.Runtime#getRuntime()
  • java.awt.Desktop#getDesktop()

另请参阅

  • Real world examples of GoF Design Patterns in Java API

更新:回答PeterMmm的(目前删除的)评论(问我怎么知道这是一个单例),检查javadoc和源代码:

Update: to answer PeterMmm's (currently deleted?) comment (which asked how I knew that it was a singleton), check the javadoc and source code:

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

它每次返回相同的实例,它有一个 private 构造函数。

It returns the same instance everytime and it has a private constructor.

这篇关于java API中的单例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆