Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Singleton Pattern trong C#

Singleton đảm bảo một lớp chỉ có một instance duy nhất và cung cấp điểm truy cập toàn cục. Trong C# có nhiều cách triển khai.

Cách 1: Eager Initialization (đơn giản, an toàn luồng)

public sealed class Singleton
{
    private static readonly Singleton _instance = new Singleton();
    
    private Singleton() { }  // Private constructor
    
    public static Singleton Instance => _instance;
    
    public void DoSomething() => Console.WriteLine("Singleton hoạt động!");
}

Cách 2: Lazy Initialization (an toàn luồng, .NET 4+)

public sealed class Singleton
{
    private static readonly Lazy _instance 
        = new Lazy(() => new Singleton());
    
    private Singleton() { }
    
    public static Singleton Instance => _instance.Value;
}

Cách 3: Double-Check Locking (cũ, phức tạp)

public sealed class Singleton
{
    private static Singleton _instance;
    private static readonly object _lock = new object();
    
    private Singleton() { }
    
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                        _instance = new Singleton();
                }
            }
            return _instance;
        }
    }
}

Sử dụng

class Program
{
    static void Main()
    {
        Singleton.Instance.DoSomething();
        // Hoặc gán cho biến
        var s = Singleton.Instance;
    }
}

Khuyến nghị: Dùng cách 1 (eager) hoặc cách 2 (lazy với Lazy<T>). Tránh double-check locking trừ khi bắt buộc .NET Framework cũ.