I was recently asked in an interview: How do you implement a Singleton design pattern in Java?
I was a little confused because there are 2 options:
1) Just have a static data member. A static member, e.g.
private static Logger logger;
will ensure that only one logger is shared among all objects of a given class.
2) Implement an instance-controller that restricts instances:
public class LoggerWrapper {
private static Logger instance = null;
private LoggerWrapper() { }
public static Logger getInstance() {
if (instance == null) {
instance = new Logger ();
}
return instance;
}
}
What is the difference between these 2 singleton approaches?