参考答案
单例模式的使用场景主要有:IO 、数据库连接、Redis 连接等。
单例模式代码的实现:
class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
单例模式调用代码:
public class Lesson7\_3 {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);
}
}
结果:
true
可见,以上单例模式在类加载的时候已经创建了,这样会影响程序的启动速度。
那如何实现单例模式的延迟加载,在使用时再创建?
单例延迟加载代码:
// 单例模式-延迟加载版
class SingletonLazy {
private static SingletonLazy instance;
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
以上为非线程安全的。
单例模式如何支持多线程?
使用 synchronized 来保证,单例模式的线程安全代码:
class SingletonLazy {
private static SingletonLazy instance;
public static synchronized SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
以上,是Java面试题【什么是单例模式】的参考答案。
输出,是最好的学习方法。
欢迎在评论区留下你的问题、笔记或知识点补充~
—end—
