Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java Pattern class use a factory method rather than constructor?

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.

like image 520
Alan Avatar asked May 13 '09 00:05

Alan


People also ask

Why do we use factory pattern in Java?

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.

What is the advantage of using a static factory method instead of a constructor to create an object?

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.

When should we use Factory Method Pattern?

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.

What is the factory design pattern Why do we use factories How do you use this design pattern in your application?

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.


1 Answers

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.

like image 66
cletus Avatar answered Sep 21 '22 19:09

cletus