Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of singleton classes in the Java APIs

What are the best examples of the Singleton design pattern in the Java APIs? Is the Runtime class a singleton?

like image 951
JavaUser Avatar asked Jun 17 '10 11:06

JavaUser


1 Answers

Only two examples comes to mind:

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

See also:

  • Real world examples of GoF Design Patterns in Java API

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

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

like image 190
BalusC Avatar answered Oct 15 '22 23:10

BalusC