Examples of singleton classes in the Java APIs

前端 未结 3 1802
闹比i
闹比i 2021-02-04 12:23

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

3条回答
  •  梦如初夏
    2021-02-04 13:13

    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 Runtime are instance 
         * methods and must be invoked with respect to the current runtime object. 
         * 
         * @return  the Runtime 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.

提交回复
热议问题