C# Design Patterns: the Singleton pattern
January 13, 2009
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(); | |
} | |
} |
I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via Github, Stackoverflow, Resume