设计模式-单例模式-单例模式
面5笔5编程实现懒汉类型的单例模式
正确答案是
class SingletonLazy {
private static SingletonLazy singletonLazy;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
try {
if (null == singletonLazy) {
// 模拟在创建对象之前做一些准备工作
Thread.sleep(1000);
synchronized (SingletonLazy.class) {
if(null == singletonLazy) {
singletonLazy = new SingletonLazy();
}
}
}
} catch (InterruptedException e) {
// TODO: handle exception
}
return singletonLazy;
}
}