• Index

单例模式

Last updated: ... / Reads: 105 Edit

单例模式是一种常见的设计模式,用于确保类只有一个实例,并提供全局访问点。在 Java 中,可以使用以下方式实现单例模式:

  1. 懒汉式单例模式(Lazy Initialization):
public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // 私有构造函数,防止其他类创建实例
    }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

在懒汉式中,实例在首次被使用时才会被创建。

  1. 饿汉式单例模式(Eager Initialization):
public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {
        // 私有构造函数,防止其他类创建实例
    }

    public static Singleton getInstance() {
        return instance;
    }
}

在饿汉式中,实例在类加载时就会被创建。

  1. 双重检查锁定单例模式(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;
    }
}

双重检查锁定单例模式结合了懒汉式和同步锁的优点,在多线程环境下也能保持高性能。

这些是单例模式的几种常见实现方式。根据具体的需求和线程安全要求,可以选择合适的方式实现单例模式。


Comments

Make a comment

  • Index