Introduction
I have been often asked this question in an interview to write a code of Singleton pattern. I have noticed that developers have the knowledge of what is Singleton pattern but often they forget the key points regarding its implementation. In this post, I will highlight the key points to remember for your upcoming interview.Implementation
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Key Points to remember
a) instance is declared as private and static
b) The constructor is declared as private
c) getInstance method is static and synchronized to make it thread free
Conclusion
In this post, we learned how to implement the Singleton pattern using Java language. We have also noted down the key points to remember.Please leave your comments in the comments box.
Comments
Post a Comment