软件单例模式
单例模式
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
例子:数据库连接池、日志记录器、应用配置对象。java实现一个demo
以下是一个线程安全的单例模式实现示例,使用双重检查锁定(Double-Checked Locking)来确保高性能和线程安全:
public class Singleton {// 1. 私有静态 volatile 实例变量private static volatile Singleton instance;// 2. 私有构造方法,防止外部直接实例化private Singleton() {// 防止通过反射创建实例if (instance != null) {throw new IllegalStateException("Singleton already initialized");}}// 3. 全局访问点public static Singleton getInstance() {// 第一次检查:避免不必要的同步if (instance == null) {synchronized (Singleton.class) {// 第二次检查:确保只有一个线程能创建实例if (instance == null) {instance = new Singleton();}}}return instance;}// 示例方法public void showMessage() {System.out.println("Hello, I am a Singleton!");}// 测试代码public static void main(String[] args) {Singleton singleton = Singleton.getInstance();singleton.showMessage();// 验证单例Singleton anotherSingleton = Singleton.getInstance();System.out.println("Is same instance? " + (singleton == anotherSingleton)); // 输出 true}
}
