问题
There's a good discussion of this in the general case.
However, I was wondering specifically why the Pattern class uses the compile static method to create an object, rather than the constructor?
Seems to me to be more intuitive to use a constructor.
回答1:
The Pattern class is newer than a lot of the stuff in the JDK. As such I believe they adopted the more modern approach of using factory methods rather than the older approach of public constructors. You can't really retrofit factory methods to existing classes.
Generally speaking, there's not a lot of reason to use a constructor over a factory method so I think that's all there was to it. Factory methods allow you to abstract object creation, which can be pretty useful.
回答2:
Why would you two Pattern instance of the same regex? A static creation method allows implementations to potentially cache Patterns sometimes returning the same object if the same regex is asked for multiple times. Compiling Patterns can be expensive. Also if additional compile methods became necessary (say different syntaxes), they could be given different names instead of a confusingly overloaded set of constructors.
回答3:
The static factory pattern is used when there is a good chance that the underlying implementation may be changed in a way that could effect the constructor. In short, factory allows for significant flexibility for the library maintainer without being tied down by binary and source compatibility on the construction side.
See http://en.wikipedia.org/wiki/Factory_method_pattern for details - especially the 'Other benefits and variants' section.
回答4:
Using a factory method for Pattern also could eventually allow the use of a 3rd party plug-in regex implementation. Unfortunately Sun has not implemented any of the features you could get when using a factory method (plug-in ability, caching).
来源:https://stackoverflow.com/questions/855518/why-does-java-pattern-class-use-a-factory-method-rather-than-constructor