javadesign-patterns

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?


Solution

  • Only two examples comes to mind:

    See also:


    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.