Friday, June 3, 2011

Singleton Design Pattern in .Net (C#)

Singleton Design Pattern
This pattern ensures that only a single instance of a given object can exist. It prevent developers from creating multiple instances of class. It is very simple patter to implement it in our applications. Go through the following example, it will give you the exact idea behind the Singleton Design Pattern.

    //sealed class cannot be inherited.
//thus we can prevent creating objects
//through its subclasses.
public sealed class MyDataContext
{
private static readonly MyDataContext _context = new MyDataContext();

//by defining a private constructor
//we cannot create an object from outside the class.
private MyDataContext()
{
}

public static MyDataContext Create()
{
return _context;
}


//Other operations.
}


Here in this example we can create an instance of MyDataContext class only by calling the Create method. We have ensure singleton by



  • declaring class as sealed

  • defining a private constructor to prevent outside object initialization

Hope all of you are now clear with Singleton Design Pattern. In my opinion this pattern is most used in Desktop Applications. It is possible to implement this in Asp.Net, I will post an article on that soon.

No comments: