为什么java的Pattern和Matcher类中没有公共构造函数?

为什么java的Pattern和Matcher类中没有公共构造函数?

问题描述:

我想知道java的Pattern和Matcher类中是否有任何特定原因没有公共构造函数?

I like to know is there any specific reason that there is no public constructor in Pattern and Matcher class of java?

谢谢

许多框架都避免在复杂对象中使用直接构造函数,而是更优雅的工厂。

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

通过'编译'正则表达式生成模式,因此您对'compile'方法进行静态调用。它初始化了所有必要的东西。匹配器特定于模式,因此由模式对象而不是由用户直接生成。

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.

这种方法的另一个潜在优势(与直接构建相比)是原则上可以通过实例化不同的Pattern和子类型来向用户透明地提供不同的匹配引擎马奇在幕后。例如,假设您对匹配固定长度字符串的正则表达式(例如,没有通配符)以及包含星号或加号的正则表达式具有不同的匹配器实现,并且存在性能差异。话虽如此,似乎实际上并不是这样,因为Matcher被定义为最终类,尽管内部结构可能与模式紧密相关。

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.