单例的五种手撕写法

2024-12-30 14:56:46   小编

单例的五种手撕写法

在编程领域中,单例模式是一种常见且实用的设计模式。它确保一个类只有一个实例存在,并提供全局访问点。下面将为您详细介绍单例的五种手撕写法。

一、懒汉式(非线程安全)

这种写法在第一次调用 getInstance 方法时才创建实例,节省了资源,但在多线程环境下可能会创建多个实例。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

二、懒汉式(线程安全)

通过给 getInstance 方法加锁,保证在多线程环境下也只有一个实例被创建,但效率相对较低。

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 Singleton instance = new Singleton();

    private Singleton() {}

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

四、双重检查锁

结合了懒汉式和线程安全的优点,通过两次判断 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;
    }
}

五、静态内部类

利用 JVM 类加载机制实现线程安全和延迟加载。

public class Singleton {
    private Singleton() {}

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

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

不同的单例写法各有优缺点,在实际开发中,需要根据具体的业务场景和性能要求选择合适的单例模式实现方式。掌握这些手撕写法,将有助于我们更好地设计和优化代码。

TAGS: 单例模式写法 手撕单例技巧 五种单例方式 单例实现方法

欢迎使用万千站长工具!

Welcome to www.zzTool.com