Java 单例模式详解

本文详细介绍了Java中单例模式的五种实现方式:懒汉式(线程不安全和线程安全)、饿汉式、枚举式、双重检查锁定式和静态内部类式。每种方式都有其特点,如懒汉式延迟初始化但需处理线程安全,饿汉式确保线程安全但可能浪费资源,枚举式是最安全的实现,双重检查锁定式兼顾安全和性能,静态内部类式实现延迟加载和线程安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式(Singleton Pattern)是一种常见的设计模式,它可以确保某个类只有一个实例,并提供对该实例的全局访问点。本文将详细介绍 Java 中所有单例模式实现,包括懒汉式、饿汉式、枚举式、双重检查锁定式、静态内部类式等。

1. 懒汉式

1.1 线程不安全

懒汉式指的是在需要获取单例实例时才进行初始化。其特点是在第一次调用 getInstance() 方法时才创建单例对象,避免了预先占用系统资源。

懒汉式有两种常见的实现方式。第一种是线程不安全的实现方式,代码如下所示:

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

这种实现方式线程不安全,多线程情况下可能会创建多个实例,因此需要进行线程安全处理。

1.2 线程安全

第二种实现方式是在 getInstance() 方法上添加 synchronized 关键字来保证线程安全,代码如下所示:

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

这种实现方式使用 synchronized 关键字来保证线程安全,在多线程情况下只会创建一个实例,但加锁会降低性能。

2. 饿汉式

饿汉式指的是在类加载时就进行初始化,无论是否需要该实例。其特点是在程序启动时就创建单例对象,可以确保线程安全,但可能会占用较多的系统资源。

饿汉式的代码实现如下:

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

3. 枚举式

枚举式是 Java 中最简洁、最安全的单例实现方式。它通过枚举类型来实现单例,可以避免线程安全问题和反射攻击等问题。

枚举式的代码实现如下:

public enum Singleton {
    INSTANCE;
    
    public void doSomething() {
        // ...
    }
}

在枚举式中,INSTANCE 是一个枚举常量,它表示单例实例。通过枚举类型的特性,保证在任何情况下都只会创建一个实例。

4. 双重检查锁定式

双重检查锁定式是一种常用的懒汉式单例实现方式,它通过双重判断来保证线程安全和性能。

双重检查锁定式的代码实现如下:

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

在双重检查锁定式中,第一次判断 instance 是否为 null 是为了避免不必要的同步,第二次判断是为了保证线程安全。使用 volatile 关键字可以确保多线程环境下的可见性。

5. 静态内部类式

静态内部类式是一种常用的懒汉式单例实现方式,它通过静态内部类来实现延迟加载和线程安全。

静态内部类式的代码实现如下:

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

    private Singleton() {}

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

在静态内部类式中,静态内部类 SingletonHolder 会在第一次使用时被加载,而 Singleton 类则是在调用 getInstance() 方法时才被加载,从而实现了延迟加载。由于静态内部类只会被加载一次,因此该实现方式也可以保证线程安全。

总结

本文介绍了 Java 中所有常见的单例模式实现方式,包括懒汉式、饿汉式、枚举式、双重检查锁定式和静态内部类式。每种实现方式都有其优缺点和适用场景,大家需要根据实际情况进行选择。无论选择哪种实现方式,都应该遵循单一责任原则和开闭原则等设计原则,以确保代码具有良好的可维护性和扩展性。

### Java Singleton Design Pattern Detailed Explanation In Java, the **Singleton design pattern** ensures that a class has only one instance and provides a global point of access to this instance. This can be particularly useful when exactly one object is needed to coordinate actions across a system. #### Characteristics of Singleton Class - The constructor should always be private. - A static method such as `getInstance()` must provide a way to get an instance of the class[^1]. #### Implementation Approaches ##### Lazy Initialization Lazy initialization creates the instance at runtime on demand rather than during startup or application load time. Here's how lazy initialization looks: ```java public class Singleton { private static Singleton uniqueInstance; private Singleton() {} public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } } ``` This approach uses synchronization within the `getInstance` method ensuring thread safety but may introduce performance overhead due to locking mechanisms every time the method gets called even after instantiation occurs once. ##### Eager Initialization Eager initialization involves creating the single instance immediately upon loading the class into memory without waiting until it’s actually required by any client code. ```java public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return INSTANCE; } } ``` While simpler, eager initialization does not support delayed loading; hence resources are allocated whether they will eventually be used or not. ##### Bill Pugh Singleton Implementation To avoid issues with multithreading while still allowing for lazy evaluation, developers often use inner helper classes like shown here: ```java public class Singleton { private Singleton(){} private static class SingletonHelper{ private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance(){ return SingletonHelper.INSTANCE; } } ``` The advantage lies in leveraging JVM guarantees about classloading behavior—classes aren't loaded unless referenced directly, thus achieving both laziness and thread-safety efficiently.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大家都说我身材好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值