I know about the general (dis)advantages of constructors vs. factory methods but there is one example where I'm really wondering why this is.
If you take a look at the Pattern
class you will see two public factory methods:
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);
}
Both of them do nothing but delegate to the constructor.
So why not just add a second constructor
public Pattern (String regex) {
this(regex, 0);
}
and omit the static factory methods?
The only reason I could think of is that you want to clarify that the constructor is already doing the "expensive" operation (i. e. the compilation) which is done by explicitly naming the method compile()
.
Or are there any general design pattern reasons for this design that I didn't notice?
Aucun commentaire:
Enregistrer un commentaire