Thread Safe Singleton Pattern

Posted: December 20, 2010 in C#, Design Patterns
Tags: ,


Simple, thread safe and the best performance solution …

public sealed class Singleton
{
    public static readonly Singleton instance = new Singleton();

    Singleton()
    {
    }     
}

  • A single constructor, which is private and parameterless to prevent other classes from creating instance.
  • The class is sealed. It may help the JIT to optimise things.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary – not used in above example and made static variable instance directly public, but for correct use we can have public static property or method to access the instance which will give more control for future
  • Explicit static constructor to tell C# compiler not to mark type as beforefieldinit – not used in above example

There are many ways of creating Singleton object. Refer below link for more details with explanation on each variation …

http://www.yoda.arachsys.com/csharp/singleton.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s