TechBubbles Microsoft Technology BLOG

Singleton Design Pattern in C#

Best known Creational Design Pattern is Singleton. We can implement this pattern in different ways. I am explaining some of the ways where we can implement in C#.

We will have the following concepts in implementing the Singleton pattern

  • We declare a private constructor which prevents other classes to create an instantiation of the singleton class. It also prevents the sub classing.
  • We declare a class as sealed so that it can not be instantiated.
  • We declare a static variable for holding the reference of a singleton class.
  • We declare a public property to return the singleton instance.
  • We declare a method for returning the message from the singleton class.

Singleton

The problem with the above code is it is not a thread –safe code. For example if two threads evaluates the if condition in the above code and both returns the true.

We will rewrite the code for thread safety

SingletonLock

The above implementation is thread safe but having the performance issue.

Every time the lock is acquired whenever you request the object.

We can write the above code with out implementing the locks as follows

image

The static constructor in C# only be called whenever you create a instance for the class.

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

Add Comment

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud