C# 单例模式的多种实现

是这样的,想请说明下,C# 单例模式的多种实现
最新回答
北极甜虾

2026-06-25 09:17:39

C# 中单例模式有多种实现方式,每种方式都有其特点和适用场景。以下是几种常见的实现方式:

  1. 饿汉式单例模式:

    特点:在类加载时就创建实例,线程安全,实现简单。

    缺点:如果实例未被使用,会造成资源浪费。

    代码示例:

    public class SingletonEager{ private static readonly SingletonEager _instance = new SingletonEager(); private SingletonEager() { } public static SingletonEager Instance { get { return _instance; } } public void DoSomething() { Console.WriteLine("饿汉式单例模式."); }}
  2. 懒汉式单例模式:

    特点:在第一次被访问时才创建实例,需要处理线程安全问题。

    实现方式:使用双重检查锁定(Double-Checked Locking)确保线程安全。

    代码示例:

    public class SingletonLazy{ private static SingletonLazy _instance; private static readonly object _lockObj = new object(); private SingletonLazy() { } public static SingletonLazy Instance { get { if (_instance == null) { lock (_lockObj) { if (_instance == null) { _instance = new SingletonLazy(); } } } return _instance; } } public void DoSomething() { Console.WriteLine("懒汉式单例模式."); }}
  3. 使用 Lazy 实现单例模式(.NET 4.0 及以上版本):

    特点:线程安全,延迟初始化,代码简洁。

    代码示例:

    public sealed class SingletonByLazy{ private static readonly Lazy<SingletonByLazy> _lazy = new Lazy<SingletonByLazy>(() => new SingletonByLazy()); private SingletonByLazy() { } public static SingletonByLazy Instance { get { return _lazy.Value; } } public void DoSomething() { Console.WriteLine("懒加载单例模式."); }}
  4. 静态初始化单例模式:

    特点:利用静态构造函数的特性确保线程安全。

    代码示例:

    public sealed class SingletonStatic{ private static readonly SingletonStatic _instance = new SingletonStatic(); static SingletonStatic() { } private SingletonStatic() { } public static SingletonStatic Instance { get { return _instance; } } public void DoSomething() { Console.WriteLine("静态初始化单例模式."); }}
  5. 完全惰性单例模式:

    特点:只有在第一次访问实例时才进行初始化,且线程安全。

    代码示例:

    public sealed class SingletonFullyLazy{ private SingletonFullyLazy() { } public static SingletonFullyLazy Instance { get { return Nested._instance; } } private class Nested { static Nested() { } internal static readonly SingletonFullyLazy _instance = new SingletonFullyLazy(); } public void DoSomething() { Console.WriteLine("完全惰性单例模式."); }}

总结:

  • 饿汉式适合实例创建成本不高且一定会被使用的场景。
  • 懒汉式适合需要延迟加载且对性能要求较高的场景,但需要注意线程安全。
  • Lazy方式是.NET 4.0及以上版本的推荐方式,简洁且线程安全。
  • 静态初始化和完全惰性方式也是线程安全的实现,适用于不同场景。

选择哪种实现方式取决于具体的应用场景和需求。