单例模式(Singleton Pattern)是一种常用的软件设计模式,其核心目的是确保一个类只有一个实例,并提供一个全局访问点。单例模式通常用于管理共享资源,如配置信息、线程池、缓存等。
单例模式的特点:
1. 全局访问点:整个程序中可以方便地访问这个唯一的实例。
2. 延迟实例化:只有在需要时才创建实例。
3. 控制实例化:防止外部通过new操作符直接创建实例。
实现单例模式的步骤:
1. 私有化构造函数:防止外部通过new创建实例。
2. 创建一个私有静态变量:用于保存类的唯一实例。
3. 提供一个公有静态方法:用于获取这个唯一实例。
单例模式的实现方式:
1. 饿汉式(Eager Initialization):
这种方式在类加载时就完成了实例化,适用于单例对象必须加载或者频繁使用的情况。
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2. 懒汉式(Lazy Initialization):
这种方式在第一次被使用时才创建实例,适用于单例对象可能不被使用的情况。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
为了避免每次调用getInstance()方法都要同步,可以使用双重检查锁定(Double-Checked Locking):
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;
}
}
3. 静态内部类(Static Nested Class):
这种方式利用了虚拟机的类加载机制来保证初始化实例时只有一个线程。
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
4. 枚举(Enum):
使用枚举实现单例模式可以避免多线程问题,并且自动支持序列化机制。
public enum Singleton {
INSTANCE;
public void doSomething() {
// do something
}
}
单例模式的优缺点:
• 优点:
• 提供了一个全局访问点。
• 减少了内存开销,因为只有一个实例。
• 可以控制实例化过程。
• 缺点:
• 没有接口,扩展困难。
• 在多线程环境下需要额外的同步处理。
• 单例类的职责过重,违反了单一职责原则。
单例模式是设计模式中的基础,理解其实现机制和适用场景对于编写高质量代码非常重要。