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.
How to follow or implement Singleton Design Pattern?
Follow the below suedo to implement singleton pattern in class:
- Create a private static variable of a class
- Create private construtor so that constructor can be called from outside.
- 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;
}
}
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