Which are the minimum changes needed to properly implement the singleton pattern?
1: public class Main { 2: private static Main m; 3: private int pageNumber; 4: static { 5: m = new Main(); 6: } /* www . ja va 2s .c o m*/ 7: public static Main getInstance() { 8: return m; 9: } 10: public int getPageNumber() { 11: return pageNumber; 12: } 13: public void setPageNumber(int newNumber) { 14: pageNumber = newNumber; 15: } 16: }
B.
This class is not a singleton because it needs a private constructor.
Having a setter method is fine.
The state of a singleton's instance variables is allowed to change.
The static initializer is fine as it runs at the same line as the declaration on line 2.
Therefore, only the constructor addition is needed, and Option B is correct.