You have two questions: when should I call the getInstance() method, and when should I create it?
If you decide whether to call a getInstance() method , this is easy. You just need to read the class documentation to find out when you should call it. For example, NumberFormat provides a constructor and getInstance() method; The getInstance() method will give you a localized NumberFormat . For Calendar , on the other hand, the constructor is protected. You must call getInstance() to get it.
If you decide to create a getInstance() method, you need to decide what you are trying to execute. Either you donβt want people to call your constructor (you create a singleton or factory ), or you donβt mind (like in NumberFormat above, where they initialize some objects for the convenience of the caller).
In short? Don't worry about creating getInstance() methods in your own code. If time arises when they are useful, you will find out. In general, if you can call the constructor of a class, you should probably do it, even if the class provides the getInstance() method.
Chris B. Jul 02 '10 at 10:08
source share