且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java API中的单例类示例

更新时间:2023-11-13 14:02:58

只有两个例子注意:

  • 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.