Which of these classes properly implement(s) the singleton pattern?
class Answer { //from w ww . j av a 2 s. c o m private static Answer instance = new Answer(); private List<String> answers = new ArrayList<>(); public static List<String> getAnswers() { return instance.answers; } } class Main { private static Main instance = new Main(); private List<String> answers = new ArrayList<>(); public static Main getMain() { return instance; } public List<String> getAnswers() { return answers; } }
D.
The singleton pattern requires that only one instance of the class exist.
Neither of these classes meets that requirement since they have the default no-argument constructor available.
There should have been a private constructor in each class.
Option D is correct.