Singleton2.java 551 B

123456789101112131415161718192021
  1. package com.sf.singleton;
  2. /**
  3. * 在使用时才创建对象
  4. * 懒汉式
  5. */
  6. public class Singleton2 {
  7. private static Singleton2 instance;
  8. private Singleton2(){}
  9. public static Singleton2 getInstance(){
  10. // 可以在第一次调用时创建对象
  11. // 如何区分是第一次 如果instance为null 再创建对象
  12. if(instance == null){
  13. instance = new Singleton2();
  14. }
  15. // 如果已经被创建过了 instance不为null 会返回上一次创建的对象
  16. return instance;
  17. }
  18. }