Static Factory Methods
Consider using Static Factory Methods Instead of Constructors
The static factory method is a method that returns an instance of the class.
Example
In this example, we will build some HTML elements using Java. Here is the base class.
|
|
Instead of providing a normal constructor, we can provide the of
static factory method:
|
|
So that, we can create new div
s using this method:
|
|
Here is the output of the demo above:
|
|
Why?
- Static Factory Methods have names - easier to know and use especially if we have multiple static factory methods VS multiple overridden constructors!
- Static Factory Methods do not require creating a new object each time - you may use some cache or a singleton behavior.
- Static Factory Methods can return an object with a type of sub-class if needed! The constructors cannot.
Why Not?
- Classes with only Static Factory Methods can not be subclassed - unless you added at least one protected or public constructor, you may need to add multiple constructors as well.
- Constructors are easier to be found and highlighted by the IDEs for developers.
Common Names
There are multiple common names for Static Factory Methods, some of them are: of
, from
, create
, getInstance
, and valueOf
.
Read more about this topic from our resource below.
Resources
- Effective Java, 3rd Edition, by Joshua Bloch - Buy from Amazon .