Difference between calling new and getInstance()

前端 未结 6 1842
一个人的身影
一个人的身影 2021-01-31 11:30

Is calling Class.getInstance() equivalent to new Class()? I know the constructor is called for the latter, but what about getInstance()? T

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 12:20

    There is no such method as Class#getInstance(). You're probably confusing it with Class#newInstance(). And yes, this does exactly the same as new on the default constructor. Here's an extract of its Javadoc:

    Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

    In code,

    Object instance = Object.class.newInstance();
    

    is the same as

    Object instance = new Object();
    

    The Class#newInstance() call actually follows the Factory Method pattern.


    Update: seeing the other answers, I realize that there's some ambiguity in your question. Well, places where a method actually named getInstance() is been used often denotes an Abstract Factory pattern. It will "under the hoods" use new or Class#newInstance() to create and return the instance of interest. It's just to hide all the details about the concrete implementations which you may not need to know about.

    Further you also see this methodname often in some (mostly homegrown) implementations of the Singleton pattern.

    See also:

    • Real world examples of GoF design patterns.

提交回复
热议问题