(一)懒汉式(线程不安全)
(1)步骤如下:
- 构造器私有化(防止new再获取对象)
- 类的内部创建对象(但是不急着实例化)
- 提供一个公有的静态方法,当使用到这个方法时,先判断对象是不是null,如果为null再去实例化对象instance(饿汉式是调用类就创建对象并且实例化,懒汉式是调用类时创建对象,调用getInstance时对象实例化)
(2)单例类代码如下:
class Singleton03{
private Singleton03(){ }
private static Singleton03 instance;
public static Singleton03 getInstance(){
if(instance==null){
instance=new Singleton03();
}
return instance;
}
}
(3)测试类代码如下
public class SingletonTest03 {
public static void main(String[] args) {
Singleton03 instance01=Singleton03.getInstance();
Singleton03 instance02=Singleton03.getInstance();
System.out.println(instance01==instance02);
System.out.println("instance01-hashCode="+instance01.hashCode());
System.out.println("instance02-hashCode="+instance02.hashCode());
}
}
(二)优缺点分析
- 起到了懒加载的效果(调用类的时候只创建对象但是不急着实例化),但是只能在单线程下使用
- 如果在多线程下,一个线程进入了if语句,还没来得及往下执行,另一个线程也通过这个if语句,这样就会产生多个实例
- 所以说:在实际开发中,不要使用这种方式
(三)与饿汉式的区别
private final static Singleton01 instance=new Singleton01();
改成了
private static Singleton03 instance;
public static Singleton03 getInstance(){
if(instance==null){
instance=new Singleton03();
}
return instance;
}