Singleton pattern

Summary

A class that only allows one instance of itself, which is accessed via a static property.

Example usage

The commonest example is an application only allowing one instance of itself, much like Windows Media Player does. Another example is a 'global' instance of a class, which contains settings or config information.

This is Jon Skeet's lazy implementation example. He has a full discussion on the various ways of implementing a singleton in C#, the example below being the final version. The full article can be found here

public sealed class Singleton
{
    Singleton()
    {
    }

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

    class Nested
    {
    	// Explicit static constructor to tell C# compiler
    	// not to mark type as beforefieldinit
    	static Nested()
    	{
    	}

    	internal static readonly Singleton instance = new Singleton();
    }
}
Last updated on 02 February 2009

Comments

blog comments powered by Disqus