Is calling Class.getInstance()
equivalent to new Class()
?
I know the constructor is called for the latter, but what about getInstance()
?
T
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:
public static DaoMappingManager getInstance() {
DaoProperties daoProperties = null;
try {
daoProperties = (DaoProperties) DaoProperties.getInstance();
} catch (PropertyException e) {
e.printStackTrace();
}
return getInstance(daoProperties);
}
public static DaoMappingManager getInstance(DaoProperties daoProperties) {
if (instance == null) {
instance = new DaoMappingManager(daoProperties);
}
return instance;
}