image.png

    1. package com.itheima.d4_static_singleinstance;
    2. public class Test2 {
    3. public static void main(String[] args) {
    4. // 目标:掌握懒汉单例的设计。理解其思想
    5. // SingleInstance2 s1 = SingleInstance2.instance;// 默认值为null
    6. // SingleInstance2 s2 = SingleInstance2.instance; // null
    7. // System.out.println(s1);
    8. // System.out.println(s2);
    9. // 这个时候已经产生了对象
    10. System.out.println(SingleInstance2.getInstance());
    11. // 将创建的对象用变量存起来
    12. SingleInstance2 s1 = SingleInstance2.getInstance();
    13. SingleInstance2 s2 = SingleInstance2.getInstance();
    14. System.out.println(s1 == s2); // 为true代表实现了懒汉单例
    15. }
    16. }
    1. package com.itheima.d4_static_singleinstance;
    2. /**
    3. * 懒汉单例
    4. */
    5. public class SingleInstance2 {
    6. /**
    7. * 2.定义一个静态的成员负责存储一个对象
    8. * 只加载一次,只有一份
    9. * 注意:最好将成员私有化,因为一开始的默认值为null,被别人调用一直为nll
    10. * 防止被别人调用,就将他私有化
    11. */
    12. // 如果像这种变量类型为:类名 的话,用来存储的都是对象
    13. private static SingleInstance2 instance; // 默认值为:null
    14. /**
    15. * 3. 提供一个方法,对外返回单例对象
    16. */
    17. public static SingleInstance2 getInstance(){
    18. if (instance == null){
    19. // 第一次来拿对象:此时需要创建对象
    20. instance = new SingleInstance2();
    21. }
    22. // 如果有对象了,就返回对象的地址给他
    23. return instance;
    24. }
    25. /**
    26. * 1. 私有化构造器(要想实现单例模式必须私有化构造器,不能被别人创建对象)
    27. */
    28. private SingleInstance2(){
    29. }
    30. }