当前,我有几个单例对象,它们在正则表达式上进行匹配,并且Patterns的定义如下:
class Foobar {
  private final Pattern firstPattern =
    Pattern.compile("some regex");
  private final Pattern secondPattern =
    Pattern.compile("some other regex");
  // more Patterns, etc.
  private Foobar() {}
  public static Foobar create() { /* singleton stuff */ }
}
但是前几天有人告诉我这是不好的风格,Pattern应该始终在类级别定义s ,而看起来像这样:
class Foobar {
  private static final Pattern FIRST_PATTERN =
    Pattern.compile("some regex");
  private static final Pattern SECOND_PATTERN =
    Pattern.compile("some other regex");
  // more Patterns, etc.
  private Foobar() {}
  public static Foobar create() { /* singleton stuff */ }
}
这个特定对象的生存期没有那么长,而我使用第一种方法的主要原因是因为,Pattern一旦对象被GC处理,坚持使用s 对我来说就没有意义。
有什么建议/想法吗?