02.单例-懒汉式


public class Dog {

private Dog() {
}

private static Dog instance;

//懒汉式加载
public static Dog getInstance() {
//通过判断对象是否被初始化,来选择是否创建对象
if (instance == null) {
instance = new Dog();
}
return instance;
}

}

static void method2() {
Dog d1 = Dog.getInstance();
Dog d2 = Dog.getInstance();
System.out.println(d1.equals(d2));
}
//测试看似安全 但是如果放在多线程里呢

 

posted @ 2025-05-29 23:08  逆流而下  阅读(8)  评论(0)    收藏  举报