Geeks With Blogs
Enterprise Architecture by Ahsan Alam

Whenever we want to implement a Singleton Pattern, we can always find examples by picking up a book on Design Patterns or by searching through the internet. Most of these implementations are very similar, and have been in use for some time. I have shown one such implementation that is traditionally being practiced in a multi-threaded environment.

Singleton the Traditional way:

public sealed class Singleton
{
      private static volatile Singleton instance = null;
      private static object syncRoot = new Object();

      private Singleton() { }  // Private constructor – cannot be instantiated

      public static Singleton Instance()
      {
             if (instance == null)  // Double check locking pattern
             {
                  lock (syncRoot)
                  {
                       if (instance == null)
                       {
                           instance = new Singleton();
                       }
                  }
             }
             return instance;
      }
}

Microsoft, on the other hand, has dramatically simplified the implementation of Singleton Pattern with enriched features in .NET. Please see below:

Singleton the .NET way:

public sealed class Singleton
{
      // Private constructor – cannot be instantiated
      private Singleton() { }
 
      // .NET will initialize static property only during first call
      // Framework guarantees thread safety on static type initialization
      // Readonly keyword prevents Instance from being 
      // modified after initialization

      public static readonly Singleton Instance = new Singleton();
}

I got one thing to say – “.Net Rocks”!!!!

Posted on Thursday, January 25, 2007 1:09 PM .NET | Back to top


Comments on this post: Singleton - Traditional way vs. .NET way

# re: Singleton - Traditional way vs. .NET way
Requesting Gravatar...
Correct me if I'm wrong, but it appears your Topics, which are underlined, are displayed after the content of the topic.
Left by Rolo on Feb 10, 2007 3:11 AM

# re: Singleton - Traditional way vs. .NET way
Requesting Gravatar...
Sorry for the confusion Rolo. I have updated the blog. I hope it makes better sense.
Left by Ahsan on Feb 10, 2007 3:10 PM

Your comment:
 (will show your gravatar)


Copyright © Ahsan Alam | Powered by: GeeksWithBlogs.net