Three examples of writing singleton patterns in C

  • 2021-06-29 11:51:58
  • OfStack

The first one is the simplest, but it doesn't take thread safety into account. It may cause problems when multithreaded, but I have never seen any mistakes and scorn me...


public class Singleton
{
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
}

The second considers thread security, but it's a little tedious, but it's absolutely formal, classic fork

public class Singleton
{
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton CreateInstance()
    {
        if(_instance == null)
        {
            lock(lockHelper)
            {
                if(_instance == null)
                     _instance = new Singleton();
            }
        }
        return _instance;
    }
}

The third may be unique to a high-level language like C#, which is surprisingly lazy

public class Singleton
{
    private Singleton(){}
    public static readonly Singleton instance = new Singleton();
}

Oh, shit!


Related articles: