Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Tuesday
Jan132009

C# Design Patterns: the 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();
    }
}

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« C# MD5 and SHA encryption wrapper class | Main | C# Design Patterns: the Abstract Factory Pattern »