tags:

views:

391

answers:

4

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.

+5  A: 

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.

cletus
+4  A: 

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.

Tom Hawtin - tackline
In general your argument is correct. But this kind of optimization should be left optional, I think. Nevertheless there are a lot of other spots where this optimization could have been applied.
ordnungswidrig
+2  A: 

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).

Karl the Pagan
+2  A: 

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.

Kevin Day