February 27, 2011

What is Singleton Design Pattern? How did you implement it?

Singleton Design Pattern class and maintains that single instance throughout the lifetime of the program. It can easily access that single object instance without creating multiple instances. The single instance provides a global point of access to it.

You need to create a private constructor to implement it

class Singleton
{
//declare only once
private static Singleton Instance = new Singleton();
public static Singleton Ins()
{
//reuse declared instance
return Instance;
}

private Singleton()
{
//No public access allowed
//Private constructor
}
}

static means shared that help to create only one instance.

There are 2 tips in singleton design pattern implementation

1. Create private constructor

2.  Create static methods  to reuse single instance of the static object.

There are situations in real world where we need only to create  one instance of the object and shared  across the clients.

Where exactly it can be used in real time ?

Singleton design patter can be used in Banking, Financial or Travel based applications where the singleton object consists of the network related information.

if our application is an online store that allows each seller to have a customized store, if implementation of the store is a singleton object,  then the singleton instance will be created for each user . This  will  avoid a seller creating multiple stores,

An ASP.NET Web Farm (multiple server deployment) is also based on the Singleton pattern. In a Web Farm, the web application uses on several web servers. The session state ( OUTPROC) is handled by a Singleton object  in the form of exe file. This exe file interacts with the ASP.NET worker process(aspnet_wp.exe)  running on each web server. Even if one of the web servers shutting down, the singleton object still maintains the session state information across all web servers in the web farm.
Singleton pattern as a LoadBalancing object.  We  can have single instance per application, per user, per role or other criteria.

2 comments:

Laxmi Narsimha Rao Manchikanti said...

It is a nice and clean example.
I think the static method static Singleton Ins() should be either "public or protected" so that it can be accessible for the outside classes/objects to use Singleton object.

You can correct me, if I am wrong.
Thank you for the nice post.

Regards
Laxmi Narsimha Rao M

Codedefiner said...

Thanks for info.
I am searching for singleton design pattern on google, I found your article which was very useful and also I found one more article for singleton design pattern at

http://www.4microsoftsolutions.com/post/Creational-Pattern-Singleton-Design-Pattern-Example-of-Singleton-Pattern-in-C.aspx

There was an error in this gadget