2

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?

gene b.
  • 10,512
  • 21
  • 115
  • 227

1 Answers1

1

The first one is not accessible outside your class. The second one can be used by classes other than the one in which its declared. As noted by Sotirios Delimanolis the instance needs to be static so that the static getInstance() methods can access it, ensuring that all callers get the same version.

Note that there are a LOT of problems with singletons and you should think hard before implementing one.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80