Test your technical skills online, appear in Virtual Interview and be ready for job!
Twitter Twitter LinkedIn YouTube Google
Be Interview ready ! | Search
Make friends on DotNetFunda.com and expand your network!
Winners

Win Prizes

Announcements
Like us on Facebook
Sponsor
Top Articles Author
Wed, 23-Apr-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
34800
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads

SingleTon Pattern in C#.net

Ragha
Posted by under Pattern and Practices category on for Intermediate level | Views : 39057 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
2 vote(s)


The Singleton pattern ensures that a class only has one instance and provides a global point of access to it from a well-known access point. The class implemented using this pattern is responsible for keeping track of its sole instance rather than relying on global variables to single instances of objects.

Singleton Pattern Code


   

namespace DesignPatterns
{
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}
}

// code to access the Singleton.
using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(Singleton.Instance.ToString());


Explanation


First, you'll notice that the Singleton's constructor is set to private. This ensures that no other code in your application will be able to create an instance of this class. This enforces the requirement that there ever only be one instance of this class.

Then, an instance member variable is defined of the same type as the class. This instance member is used to hold the only instance of our class. The variable is static so that it is defined only once. In the .NET Framework, static variables are defined at a point before their first use (that's the actual description of their implementation). Also, the instance variable is readonly so that it cannot be modified - not even by any code that you may write in the class's implementation.

And, a public Instance property is defined with only a get method that way callers can access the instance of this class without ever being able to change it. The property is also static to provide global access from anywhere in your program. This ensures the global point of access requirement for the Singleton.

Finally, to test the code, you can run code that accesses your Singleton class. As you can see above, it's easy enough to get at the instance of your class:

Singleton.Instance;

Place a breakpoint in instance member variable definition and another one in the Instance property get code, then run the Debugger on this code. You will notice that the member variable creation is hit just before the call to the Instance property. Also, if you place multiple calls to Singleton.Instance, you will notice that the instance member variable is only the first time, all other calls just return the cached instance variable.

And, that is the only way to get an instance of a singleton class. If you try to create an instance of the Singleton class using the new operator:

Singleton NewInstance = new Singleton();

Than, you will get a compiler error stating that the class cannot be created because the constructor is inaccessible due to its protection level.

Thread-Safe Singleton Code

The previous code is the simplest implementation of a Singleton and can be used for most purposes. Typical WinForms applications runs in the UI thread, so the simple singleton will provide you with the functionality that you're looking for. However, if you are creating a multi-threaded application that needs to access a singleton across all of its threads, then you will need to create a thread-safe singleton class instead. What you gain in functionality comes at the cost of some performance, so you shouldn't use this form of the class unless you actually intend to use the class from multiple threads.

namespace DesignPatterns

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

}

public static MTSingleton Instance
{
get
{
if (instance == null)
{
lock(syncRoot)
{
if (instance == null)
instance = new MTSingleton();
}
}
return instance;
}
}
}
}
// code to access the Singleton.

using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(MTSingleton.Instance.ToString());



As you can see, this class is similar in structure to the Singleton class. The instance member variable is no longer set at creation time, but in the Instance property instead. The instance variable is declared to be volatile in order to assure that the assignment of instance complete before the instance can be accessed.

The syncRoot object is used to lock on. The lock ensures that only one thread can access the instance creation code at once. That way, you won't get into a situation where two different threads are trying to create the singleton simultaneously.

And, you'll notice that we double-check the existence of the instance variable within the locked code to be sure that exactly one instance is ever created.

Finally, in your application code, access to the MTSingleton class is done in exactly the same way as with the simple singleton.


Conclusion

The Singleton design pattern has proven to be a useful pattern in many programs that I've written. Now, the code in this tutorial shows how to implement that same pattern in the .NET Framework.
Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:




About the Author

Ragha

Full Name: chinni chinnari
Member Level: Starter
Member Status: Member
Member Since: 3/27/2008 6:28:15 AM
Country:

Login to vote for this post.

Comments or Responses


Login to post response.

Comments / Responses
Select text & click toolbar to format. Formatting appears in viewmode only. HTML Tags are not allowed.
Bold Italic Underline Paragraph Title Code  Link 
 Wait ... Processing ..... please wait.

Comment using Facebook