当前位置:网站首页>Function of getinstance() method

Function of getinstance() method

2022-06-25 14:48:00 Happy Jiajia

getInstance() The role of methods
getInstance() Refers to instantiation , And new similar , But in new There is a big difference

 // Instantiation 
 public static DBConnect instance;

 public static DBConnect getInstance(){

  if (instance == null) {
      instance = new DBconnect();
  }
  return instance;
 }

getInstance In singleton mode ( Make sure there is only one instance of a class , And provide a global access point to access it ) Common in classes , Used to generate unique instances ,getInstance Tend to be static Of .
 Generally used for relatively large 、 Complex objects , Initialize only once , and getInstance It ensures that each call returns the same object .

getInstance() and new The difference between ##

  * (1)  Object is used through getInstance Get without having to define , You don't need to delete;
  * (2)new  Be sure to generate a new object , Allocate memory ;getInstance()  You don't have to create... Again , It can give you an existing reference , This is better than new;
  * (3) new After creation, it can only be used once , and getInstance() Can be used across stack areas , Or remote cross regional use . therefore getInstance() Usually create static Of static instance methods .
原网站

版权声明
本文为[Happy Jiajia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200519091548.html