Notes

Design Patterns - Singleton

author: Paul Kim

categories: design-patterns, csharp

tags: design-patterns, csharp

Singleton

using System;

public class Singleton
{
  private static Singleton instance;

  private Singleton() {}

  public static Singleton Instance
  {
    get
    {
      if (instance == null)
      {
        instance = new Singleton();
      }
      return instance;
    }
  }
}

Static Initialization

The main disadvantage of the above implementation is that it is not safe for multithreaded environments. However, C# in combination with the common language runtime provides a static initialization approach, which circumvents these issues without requiring the developer to explicitly code for thread safety.

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

  private Singleton(){}

  public static Singleton Instance
  {
    get
    {
      return instance;
    }
  }
}

Multithreaded Singleton

The following implementation allows only a single thread to enter the critical area, which the lock block identifies. This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.

using System;

public sealed class Singleton
{
  private static volatile Singleton instance;
  private static object syncRoot = new Object();

  private Singleton() {}

  public static Singleton Instance
  {
    get
    {
      if (instance == null)
      {
        lock (syncRoot)
        {
          if (instance == null)
            instance = new Singleton();
        }
      }

      return instance;
    }
  }
}
Source

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.