There's a good discussion of this in the general case.
However, I was wondering specifically why the Pattern
class uses the compile
static method to create an object, rather than the constructor?
Seems to me to be more intuitive to use a constructor.
Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.
Another advantage of static factories is that, unlike constructors, they are not required to return a new object every time they are invoked. This is extremely useful when working with immutable classes to provide constant objects for common used values and avoid creating unnecessary duplicate objects.
The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.
Factory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class.
The Pattern class is newer than a lot of the stuff in the JDK. As such I believe they adopted the more modern approach of using factory methods rather than the older approach of public constructors. You can't really retrofit factory methods to existing classes.
Generally speaking, there's not a lot of reason to use a constructor over a factory method so I think that's all there was to it. Factory methods allow you to abstract object creation, which can be pretty useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With