Singleton Pattern

By Michael Flanakin @ 7:17 AM :: 6284 Views :: .NET 1.x, .NET 2.0, Patterns, Proven Practices :: Digg it!

Problem

You need to provide access to one and only one instance of a specific resource.

Solution

Create a class that can only be initialized internally (to the class) and expose a static member to access the single instance of the class.

The singleton pattern is perhaps the simplest of all design patterns, which makes it a perfect starting point for those wrapping their heads around patterns. As a matter of fact, chances are you've already implemented the pattern without even realizing it. In my mind, there are two versions of the singleton pattern; I'll refer to them as startup-initialized and first access singletons. You can probably imagine how these might work: the startup-initialized singleton initializes the singleton either in a static constructor or via the field declaration, while the first access singleton uses a property or method to initialize the field the first time its accessor is called.

Singleton Pattern Class Diagram

Startup-Initialized Singleton

/// <summary>
/// Startup-initialized singleton example.
/// </summary>

internal sealed class StartupInitializedSingleton
{
  /// <summary>
  /// The sole instnace of the class.
  /// </summary>

  public static readonly StartupInitializedSingleton Instance = new StartupInitializedSingleton();


  /// <summary>
  /// Initializes a new instance of the <see cref="StartupInitializedSingleton"/> class.
  /// </summary>

  private StartupInitializedSingleton()
  { }
}

First Access Singleton

/// <summary>
/// First access-initialized singleton example.
/// </summary>

internal sealed class FirstAccessSingleton
{
  private static FirstAccessSingleton _instance;


  /// <summary>
  /// Initializes a new instance of the <see cref="FirstAccessSingleton"/> class.
  /// </summary>

  private FirstAccessSingleton()
  { }


  /// <summary>
  /// Gets the sole instnace of the <see cref="FirstAccessSingleton"/> class.
  /// </summary>
  /// The instance.

  public static FirstAccessSingleton Instance
  {
    get
    {
      if (_instance == null)
        _instance = new FirstAccessSingleton();
      return _instance;
    }
  }
}