I'm going to start by saying that I understand that programming in mostly class functions and variables can be harmful to object-orientation, and that most of the time an instance is preferred. I'll be using Java as my language for this question, but it should apply to any language which makes the distinction between class and instance scopes.
But there are still times when only a single instance is wanted, which calls for the Singleton pattern:
public class Singleton1 { private static Singleton1 instance; private Object myObject; private Singleton1() { myObject = new Object(); // other initializations here } public static getInstance() { if (instance == null) instance = new Singleton(); return instance; } public Object getMyObject() { return myObject; } // and so on with the non-static public and private methods }
This will be used as such:
Singleton1 singleton1 = Singleton1.instance(); singleton1.getMyObject(); // any other method called like singleton1.method(args);
This pattern forces programmers using the Singleton1
class to get instances via Singleton1.getInstance()
instead of the usual new Singleton1()
, since the only constructor is private. The main benefit of this is guaranteeing that there is only one instance of Singleton1
being used, and so any one modification rings true everywhere in the program.
My question is, why go through the rigamarole of keeping the constructor and instance private, when the static
modifier takes care of all this already? See my example counterpoint below:
public class Singleton2 { private static Object myObject; static { myObject = new Object(); // other initializations here } private Singleton2(){/*nothing*/} public static Object getMyObject() { return myObject; } // and so on with the static public and private methods }
This will be used as such:
Singleton2.getMyObject(); // any other method called like Singleton2.method(args);
To me, this seems like less code and easier to keep up with.
Some hold that the Singleton Pattern is always an anti-pattern. What do you think?
), I am not sure if it addresses the same concerns as mine.