6

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Alan
  • 2,140
  • 1
  • 24
  • 30
  • For more info, see article by [Dr. Joshua Bloch](https://en.wikipedia.org/wiki/Joshua_Bloch), excerpting his book *Effective Java* (2e): [*Creating and Destroying Java Objects – Item 1: Consider static factory methods instead of constructors*](https://www.informit.com/articles/article.aspx?p=1216151) – Basil Bourque Mar 06 '18 at 04:48

4 Answers4

9

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
  • 616,129
  • 168
  • 910
  • 942
6

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
  • 145,806
  • 30
  • 211
  • 305
  • 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 May 13 '09 at 08:13
5

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
  • 16,067
  • 8
  • 44
  • 68
2

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
  • 1,944
  • 17
  • 17