Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Implement Singleton Design Pattern ใน C#

Singleton Pattern (Creational) ให้ Class มี Instance เพียง **1 ตัว** ตลอด Lifetime ของ Application

Implementation Guidelines

  1. Sealed Class - ป้องกัน Inheritance
  2. Private Constructor - ป้องกัน New จากภายนอก
  3. Static Instance Field - เก็บ Instance เดียว
  4. Static Property/Method - Access Point (Lazy Initialization)

ตัวอย่าง Thread-Safe (Basic)

public sealed class Singleton
{
    private static int _counter = 0;
    private static Singleton _instance = null;
    
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Singleton();
            return _instance;
        }
    }
    
    private Singleton()
    {
        _counter++;
        Console.WriteLine($"Counter: {_counter}");
    }
    
    public void Print(string message) => Console.WriteLine(message);
}

// Usage
var s1 = Singleton.Instance; // Counter: 1
s1.Print("From Facebook");

var s2 = Singleton.Instance; // No new instance
s2.Print("From Twitter");

Output

Counter: 1
From Facebook
From Twitter

Counter เพิ่มแค่ครั้งแรก → Instance เดียว

Thread-Safe Version (Double-Check Locking)

private static readonly object _lock = new object();
private static Singleton _instance;

public static Singleton Instance
{
    get
    {
        if (_instance == null)
        {
            lock (_lock)
            {
                if (_instance == null)
                    _instance = new Singleton();
            }
        }
        return _instance;
    }
}

Modern C# (Lazy<T>)

private static readonly Lazy _instance = 
    new Lazy(() => new Singleton());

public static Singleton Instance => _instance.Value;