开发者

Why are there no public constructors in Pattern and Matcher classes of java?

I like to know is there any specific reason that there is no publ开发者_如何学Goic constructor in Pattern and Matcher class of java?

Thanks


Many frameworks avoid the use of direct constructors for complex objects, preferring instead more elegant factories.

A pattern is generated by 'compiling' a regular expression, so you make a static call to the 'compile' method. It initializes everything that is necessary. A matcher is specific to a pattern, and therefore generated by the pattern object rather than directly by the user.

If the matcher had a constructor that took a pattern, the matcher's constructor might have had to access non-public fields of the pattern object.

Another potential advantage of this approach (compared to direct construction) is that it is in principle possible to provide different matching engines transparently to the user by instantiating different subtypes of Pattern and Matcher behind the scenes. For example, suppose that you had different matcher implementations for regular expressions that match a fixed-length string (e.g., no wildcards), and for regular expressions that contain an asterisk or a plus, and that there was a performance difference. That being said, it doesn't seem like this actually takes place since the Matcher is defined as a final class, though it is likely that the internals are closely bounded to the pattern.


I haven't looked at the implementation of either classes, but I would assume that Pattern.compile() is static so the class can cache recently compiled patterns, instead of instantiating a new object each time (i.e a flyweight).


The source code for compile() in java.util.regex.Pattern is:

public static Pattern compile(String regex) {
    return new Pattern(regex, 0);
}

and

public static Pattern compile(String regex, int flags) {
    return new Pattern(regex, flags);
}

Which means that the two static methods are invoking the private constructor. I can see no real advantage in this, as opposed to simply making the constructors themselves public.

The only public way of creating a Matcher is from a Pattern object, through the pattern.matcher() method, which makes sense in that a Matcher only exists within the context of a Pattern.


its a static (or final) class. everything you need can be done with compile() and matcher() methods.


In my opinion the reason for this has more to do with semantics. When you read Pattern.compile(), it conveys the fact that your input will be validated and converted to an internal representation, the same message is probably not conveyed when saying new Pattern().

On the patterns and regex fronts this could be important because of the long historical shadow that perl casts, comparisons to which are abundantly documented in the API docs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜