Pattern类没有公共构造函数

Pattern类没有公共构造函数

本文介绍了Java Pattern类没有公共构造函数,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在审查Java Regex 库,感到惊讶的是 Pattern 类没有公开我多年来一直认为理所当然的构造函数。

I've been reviewing Java Regex Library, surprised by the fact the Pattern class does not have a public constructor which I've taken for granted for years.

我怀疑使用静态 compile 方法的一个原因支持构造函数可能是构造函数总是返回一个新对象,而静态方法可能返回一个先前创建的(和缓存的)对象,只要模式字符串是相同的。

One reason I suspect the static compile method is being used in favor of constructor could be that constructor would always return a new object while a static method might return a previously created (and cached) object provided that the pattern string is the same.

但是,情况并非如下所示。

However, it is not the case as demonstrated by the following.

public class PatternCompiler {
    public static void main(String[] args) {
        Pattern first = Pattern.compile(".");
        Pattern second = Pattern.compile(".");
        if (first == second) {
            System.out.println("The same object has been reused!");
        } else {
            System.out.println("Why not just use constructor?");
        }
    }
}

使用背后的任何其他强大理由构造函数的静态方法?

Any other strong rationales behind using static method over constructor?

编辑:我找到了。那里的答案都没有说服我。通过阅读所有答案,我感觉静态方法相对于公共构造函数在创建对象方面具有相当多的优势,而不是相反。真的吗?如果是这样,我将为我的每个类创建这样的静态方法,并安全地假设它更具可读性和灵活性。

Edit: I found a related question here. None of the answers there convinced me either. Reading through all answers, I get a feeling that a static method has quite a few advantages over a public constructor regarding creating an object but not the other way around. Is that true? If so, I'm gonna create such static methods for each one of my classes and safely assume that it's both more readable and flexible.

推荐答案

通常,由于以下三个原因之一,类不具有公共构造函数:

Generally, a class won't have a public constructor for one of three reasons:


  • 该类是实用程序类,并且存在没有理由将其实例化(例如,java.lang.Math)。

  • 实例化可能失败,构造函数无法返回 null

  • 静态方法阐明了实例化过程中发生的意义。

Pattern 类中,第三种情况适用 - 静态编译方法仅用于清晰。从解释的角度来看,通过 new Pattern(..)构建模式是没有意义的,因为有一个复杂的过程继续创建一个新的模式。为了解释这个过程,静态方法名为 compile ,因为正则表达式正则编译以创建模式。

In the class of Pattern, the third case is applicable--the static compile method is used solely for clarity. Constructing a pattern via new Pattern(..) doesn't make sense from an explanatory point of view, because there's a sophisticated process which goes on to create a new Pattern. To explain this process, the static method is named compile, because the regex is essentially compiled to create the pattern.

简而言之,没有编程目的使 Pattern 只能通过静态方法构造。

In short, there is no programmatic purpose for making Pattern only constructable via a static method.

这篇关于Java Pattern类没有公共构造函数,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:41