Is calling Class.getInstance()
equivalent to new Class()
?
I know the constructor is called for the latter, but what about getInstance()
?
Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
For start:
newInstance()
is astatic method
. This means you can access to it without creating new class directly! And it creates that class itself "with necessary inits" (via an innernew myClass()
). This means you can add somenewInstance
methods (newInstance4usage1, newInstance4usage2,...) for different needs that per static method creates class with different initialization. Sometimes, this helps class's user (final programmer) to creating class without any worry and very comfortable.This helps really when the init process is complex or has important or or usual levels. this method don't prevent from creating class by
new
keyword.I like it!
Excuse me for slow answering, I am typing with my mobile phone!
Absolutely (usually) not.
getInstance
is the static method often used with the Singleton Pattern in Java. Thenew
keyword actually creates a new object. At some point there must be anew
(although there are a few other methods to instantiate new objects) to actually create the object thatgetInstance
returns.Yes, this is often used in Singleton Pattern. It`s used when You need only ONE instance of a class. Using getInstance() is preferable, because implementations of this method may check is there active instance of class and return it instead of creating new one. It may save some memory. Like in this example:
Some abstract classes have getInstance() methods because you can't instantiate an abstract class by using new keyword.
In the context of an abstract class, a
getInstance()
method may represent the factory method pattern. An example is the abstractCalendar
class, which includes static factory methods and a concrete subclass.There is no such method as
Class#getInstance()
. You're probably confusing it withClass#newInstance()
. And yes, this does exactly the same asnew
on the default constructor. Here's an extract of its Javadoc:In code,
is the same as
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" usenew
orClass#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: