Java设计模式之单例模式(Singleton)

48 阅读1分钟

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

1. 懒汉式(线程不安全):

这种方式在第一次调用getInstance()方法时才会创建实例,但这种方式在多线程环境下是不安全的。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

2. 懒汉式(线程安全):

通过在getInstance()方法上加锁,确保多线程环境下的线程安全。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

3. 饿汉式 :

这种方式在类加载时就创建实例,是线程安全的,但不管是否需要,类都会创建实例。

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

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

4. 双重检查锁定(Double-Checked Locking):

这种方式结合了懒汉式和饿汉式的优点,既保证了线程安全,又避免了在每次调用getInstance()时进行同步。

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;
    }
}

5. 静态内部类 :

这种方式利用了类加载机制来实现线程安全的单例模式。

public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

6. 枚举 :

使用枚举实现单例模式,既简单又线程安全。

public enum Singleton {
    INSTANCE;
    
    // 可以添加其他方法
}

每种实现方式都有其适用场景和优缺点,根据具体需求选择合适的实现方式。