懒汉式单例设计模式

发布时间 2023-05-28 16:00:35作者: Karlshell
package itheima;

public class Test1 {
    //掌握懒汉式单例的写法
    public static void main(String[] args) {
        B b1=B.getInstance();//第一次拿对象
        B b2=B.getInstance();
        System.out.println(b1==b2);
    }
}
package itheima;

public class B {
    //2.定义一个类变量,用于储存这个类的一个对象
    private static B b;

    //1.把类的构造器私有
    private B(){

    }
    //3.定义一个类方法,这个方法要保证第一次调用时才创建一个对象,后面调用时都会用这同一个对象返回
    public static B getInstance(){
        if (b==null){
            b=new B();
        }
        return b;
    }
}