Difference between calling new and getInstance()

前端 未结 6 1845
一个人的身影
一个人的身影 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:35

    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;
    }
    

提交回复
热议问题