Design Patterns 101: The Singleton

Quick, give me an implementation of a Singleton in C# or Java. You should be able to do this in under a minute. Take a break and write down your best implementation of a Singleton. Don't look ahead and give it your best attempt¦ How did you do? Ask yourself the following questions.

  1. Is your implementation thread safe?
  2. Is it being initialized lazily?
  3. Should you prevent inheritance?
  4. How do you prevent inheritance?

Let's look at the "ideal" C# implementation of a Singleton.

// Singleton 
// 3. Yes.
// 4. Class is marked sealed to prevent inheritance.
sealed class Singleton {

// 1. Static members are lazily initialized. 
// 2. Static members in .NET are guaranteed to be thread safe. 
private static readonly Singleton instance = new Singleton(); // Note: constructor is private.
private Singleton() {} 

public static Singleton GetInstance() { return instance; }

Knowing how to properly implement the Singleton design pattern in C# reveals important details about how the language works. If you don't prevent inheritance then someone could create a subclass that breaks the intent of having only one instance of a class. So you must be familiar with the sealed keyword. In other languages you have to deal with synchronization issues which you don't have to in C# when using static member variables. C# gives you a lot of bang for your buck.