Wednesday, February 10, 2010
Implementing Singleton Design Pattern in C# application
Introduction
Sometime we need to create only one object of any class in our application then we need to implement Singleton design pattern to achieve this.
For an example, you have logging functionality which takes value as a parameter and store information in external device (like database or xml file or flat file). This logging class doesn’t have any state value. You can design that class using singleton design pattern.
Problem and solution
First problem is that you need to be sure that your class must be initializing once and the reference is available at anytime so your application can use that reference to use singleton class method.
You can solve the above problem using private constructor. When you define private constructor then nobody can initialize object of that class. (Make sure that singleton class doesn’t have any public constructor).
public class SingletonTest
{
private SingletonTest()
{
}
}
Second problem, if you create private constructor then how can we initialize the class first time when we need it?
We can create and initialize object of singleton class (which have only private constructor) within that class. To achieve this we need to implement one public static method which will return object of Singleton class.
public class SingletonTest
{
private static SingletonTest singletonTest = null;
private SingletonTest()
{
}
public static SingletonTest RetrieveObject()
{
if (singletonTest == null)
singletonTest = new SingletonTest();
return singletonTest;
}
}
Now, we can create and initialize object of our singleton class using below code:
SingletonTest singletonTest = SingletonTest.RetrieveObject();
When user will call this method first time, this method will create new object of SingletonTest class and assign it to private static variable and return that variable.
When user will call the same method again, this method will check that the private static variable is initialized. If private static variable is initialized then it will return it. In our case it initialized already when user called this first time.
So it confirms that our SingletonTest class has only one reference during whole application life cycle.
Labels:
.Net 2008,
C#,
Design Pattern,
Microsoft .Net,
Private Constructor,
Singleton
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment