简体   繁体   中英

Why do some classes like the java regex Pattern class do not have any public constructors?

The Pattern class requires you to use it's public static compile() method in order to create a Pattern . What is the reasoning behind this? Also, is this a good example of the Factory design pattern?

In the case of Pattern mostly because because

  1. The naming is more precise than just new Pattern()
  2. Using a factory method allows the standard implementors to change the way a Pattern is created in the future.
  3. It's likely that the way it's implemented now is in some ways more efficient than just creating a new instance. Compiling a regexp to a state machine is probably an expensive process, so they will probably have found ways to mitigate this.

In general, the current wisdom is to favor static factory methods over constructors, especially in API classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM