This content has been marked as final. Show 2 replies
Hm, caching comes to mind. Using the factory method the backing logic can store precompiled versions of the regex pattern.
The answer is very generic though: you do it when it seems like it is a good idea (which over 15 years later might not be true anymore, who knows). For certainty you would have to look at the code behind the Pattern class, the original designer of that class is not around to answer you. Note that there are plenty of people who come in here stomping their feet and raving "WHY IS IT DONE LIKE THIS" when talking about classes that were designed more than 10 years ago; its a bit too late to discuss such things, what matters is that we're stuck with it.
(1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?1. As the other author mentioned, caching is one reason.
2. With such caching, you don't need to take trouble in passing the reference of a cached object(s) to many places in your code. From anywhere in your code base, you can simply invoke the method, the object will come. In essence, the static method provides a global point of access to one or more pre-created (or cached) objects. Hence, the static method simplifies access to the object.
3. Sometimes, the actual class instantiated is not the same as the one with the static method. This allows abstraction of underlying variations. For example, when you say Pattern.compile ("X[0-9]+X") , the returned object type can be different in Windows and Linux (Most probably Pattern class doesn't work like that, but I am showing you a use case. May be Runtime.getRuntime() does actually work like that.). You find this abstraction of variations in many places. Take for example, FacesContext.getExternalContext() method (this is from JSF API). ExternalContext documentation says this:
"This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment."
Edited by: Kamal Wickramanayake on Oct 24, 2012 8:04 AM