2026-06-25 09:17:39
C# 中单例模式有多种实现方式,每种方式都有其特点和适用场景。以下是几种常见的实现方式:
饿汉式单例模式:
特点:在类加载时就创建实例,线程安全,实现简单。
缺点:如果实例未被使用,会造成资源浪费。
代码示例:
public class SingletonEager{ private static readonly SingletonEager _instance = new SingletonEager(); private SingletonEager() { } public static SingletonEager Instance { get { return _instance; } } public void DoSomething() { Console.WriteLine("饿汉式单例模式."); }}懒汉式单例模式:
特点:在第一次被访问时才创建实例,需要处理线程安全问题。
实现方式:使用双重检查锁定(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("懒汉式单例模式."); }}使用 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("懒加载单例模式."); }}静态初始化单例模式:
特点:利用静态构造函数的特性确保线程安全。
代码示例:
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("静态初始化单例模式."); }}完全惰性单例模式:
特点:只有在第一次访问实例时才进行初始化,且线程安全。
代码示例:
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("完全惰性单例模式."); }}总结:
选择哪种实现方式取决于具体的应用场景和需求。