Examples of singleton classes in the Java APIs

前端 未结 3 1807
闹比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:08

    This is for Swing : SingleFrameApplication. Check out this presentation it wonderfully describes how does it work.

    0 讨论(0)
  • 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 <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.

    0 讨论(0)
  • 2021-02-04 13:17

    Note singletons should be used with care and reflection. Consider the arguments against singletons and your situation before you implement one. Overuse of singletons is an anti-pattern - similar to global variables.

    Singleton Wiki Article

    Java Dev on Singletons

    Why Singletons are Evil

    I've used them in the past and see some benefit to them. I've also been highly annoyed when trying to do test driven development with them around that's one area where they are evil. Also inheriting from them results in some hard to understand behaviour - at least in Python - I don't know for sure in Java. Generally you just don't do it because of that. So like threading these seem like a great idea at first and then you run into the pitfalls and realize well maybe this isn't so good after all.

    0 讨论(0)
提交回复
热议问题