返回

单例模式精粹:剖析 Java 和 Kotlin 中的 9 种实现方式

Android

引言

在软件开发领域,单例模式是一种设计模式,旨在确保特定类仅有一个实例,而且由类本身进行实例化并供整个系统使用。这种模式常用于确保应用程序状态的全局一致性、资源管理和对象池等场景。

本文将深入探讨单例模式,分析其在 Java 和 Kotlin 中的 6+3 种实现方式,为读者提供全面且深入的了解。

public class Singleton {

    private static Singleton instance;

    private Singleton() {}

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

优点: 只有在第一次需要实例时才创建,提高了内存效率。

缺点: 非线程安全,并发环境下可能产生多个实例。

public class Singleton {

    private static Singleton instance;

    private Singleton() {}

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

优点: 线程安全,解决了非线程安全版本的问题。

缺点: 同步锁导致性能开销,特别是高并发环境下。

public class Singleton {

    private static final Singleton instance = new Singleton();

    private Singleton() {}

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

优点: 线程安全,无需同步,性能优于懒汉式线程安全版本。

缺点: 无论是否需要,始终创建实例,可能造成资源浪费。

public class Singleton {

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

    private Singleton() {}

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

优点: 线程安全,性能较优,避免了直接同步。

缺点: 内部类的创建过程相对复杂。

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

优点: 线程安全,同时避免了过度的同步,性能优异。

缺点: 代码略微复杂,实现依赖 Java 内存模型。

object Singleton {

    val instance: Singleton by lazy {
        Singleton()
    }
}

优点: 语法简洁,易于使用。

缺点: 与 Java 的懒汉式线程安全版本类似,并发环境下可能存在创建多个实例的风险。

class Singleton private constructor() {

    companion object {
        val instance by lazy {
            Singleton()
        }
    }
}

优点: 语法简洁,确保线程安全。

缺点: 无法直接访问私有构造函数。

enum class Singleton {

    INSTANCE;
}

优点: 线程安全,性能优异,单例是枚举类的唯一实例。

缺点: 无法自定义构造函数参数。

单例模式是一种强大的设计模式,可确保类只有一个实例。在 Java 和 Kotlin 中,有多种实现方式,每种方式都有其优点和缺点。开发者应根据特定场景和需求选择最合适的实现方式。