设计模式是解决特定问题的成熟方案。掌握它们能让代码更易扩展、更健壮。
1. 单例模式 (Singleton)
保证一个类只有一个实例。
- 场景: 数据库连接池、Spring Bean(默认单例)、配置管理器。
- 实现: 双重检查锁(Double Check Lock)。
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
