Which of these classes best implement(s) the singleton pattern?
class Answer { //from w w w.j a v a 2 s.c o m private static Answer instance = new Answer(); private List<String> answers = new ArrayList<>(); private Answer() {} public Answer getAnswer() { return instance; } public List<String> getAnswers() { return answers; } } class Main { private static Main instance = new Main(); private List<String> answers = new ArrayList<>(); private Main() {} public static Main getMain() { return instance; } public List<String> getAnswers() { return answers; } }
B.
The singleton pattern requires that only one instance of the class exist.
The Answer class is close.
getAnswer()
is not static, so you can't retrieve the instance.
Option B is the answer because Main is a correct implementation.
It has a static variable representing the one instance and a static method to retrieve it.