单例模式的 7 种实现方式,你了解多少?

2024-12-31 13:49:56   小编

单例模式的 7 种实现方式,你了解多少?

在编程领域中,单例模式是一种常见且实用的设计模式。它确保一个类只有一个实例存在,并提供全局访问点。下面让我们来深入探讨单例模式的 7 种实现方式。

  1. 饿汉式 这种方式在类加载时就创建实例,简单直接,但可能造成资源浪费,如果实例的创建开销较大且不一定会被使用,就不太合适。
public class Singleton1 {
    private static Singleton1 instance = new Singleton1();

    private Singleton1() {}

    public static Singleton1 getInstance() {
        return instance;
    }
}
  1. 懒汉式(线程不安全) 在需要的时候才创建实例,但在多线程环境下可能会创建多个实例。
public class Singleton2 {
    private static Singleton2 instance;

    private Singleton2() {}

    public static Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}
  1. 懒汉式(线程安全) 通过同步方法来保证线程安全,但效率较低。
public class Singleton3 {
    private static Singleton3 instance;

    private Singleton3() {}

    public static synchronized Singleton3 getInstance() {
        if (instance == null) {
            instance = new Singleton3();
        }
        return instance;
    }
}
  1. 双重检查锁 结合了懒汉式和同步锁,提高了性能。
public class Singleton4 {
    private static volatile Singleton4 instance;

    private Singleton4() {}

    public static Singleton4 getInstance() {
        if (instance == null) {
            synchronized (Singleton4.class) {
                if (instance == null) {
                    instance = new Singleton4();
                }
            }
        }
        return instance;
    }
}
  1. 静态内部类 利用了类加载机制,实现了延迟加载和线程安全。
public class Singleton5 {
    private Singleton5() {}

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

    public static Singleton5 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 枚举 简洁且线程安全。
public enum Singleton6 {
    INSTANCE;
}
  1. 注册式单例 通过容器来管理单例对象,灵活性较高。

不同的实现方式各有优缺点,需要根据具体的应用场景来选择。在实际开发中,要综合考虑性能、线程安全、资源消耗等因素,选择最合适的单例模式实现方式。

深入理解和掌握单例模式的多种实现方式,能够让我们在编程中更加灵活和高效地运用这一设计模式,提升代码的质量和可维护性。

TAGS: 单例模式特点 单例模式实现方式 单例模式应用场景 单例模式优缺点

欢迎使用万千站长工具!

Welcome to www.zzTool.com