Friday 4 May 2012

What is Singleton Design Pattern?

Singleton Pattern is one of the well known and ask most of the times in interview questions in design patterns, if I am not wrong then 90  percent of the cases singleton pattern is asked, but I don't understand why this is so famous may be due to its criticality and  frequently occur problem in software coding, WHY, WHY WHY...

Is any one has the answer, Think about Performance!!!.

Performance is one of the target for any application and singleton pattern plays a vital role in improving performance, Imagine the application with lots of objects created and none of the object is destroyed by their own and there is  mechanism to destroy of these objects, Now I don't think anyone will agree for such design or application. Yes here is Singleton pattern come in picture. Create a single instance of a class and use it through out the application.

One scenario I am missing here what will happen, when no of component of application uses single instance of a class, Doesn't this hamper the application performance. Do we need to create every class as singleton.

I think No No No. So question is Where to use Singleton pattern?

Singleton pattern is generally used to service instance independent or static data where multiple threads can access data at same time. example can be logging class.

Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the Singleton can be easily adjusted to allow more connections.


How to follow or implement Singleton Design Pattern?

Follow the below suedo to implement singleton pattern in class:
  1. Create a private static variable of a class
  2. Create private construtor so that constructor can be called from outside.
  3. Create a public method which will return the instance of class created at step 1.

public class MySingleton { 
 private static MySingleton _instance; 

 private MySingleton() { 
 } 

 public static synchronized MySingleton getInstance() { 
  if (_instance==null) { 
   _instance = new MySingleton(); 
  } 
  return _instance; 
 } 

Thanks for the reading please do comment to facilitate you better.

0 comments:

Post a Comment

Site Search