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.
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
divs using this method:
Here is the output of the demo above:
- 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.
- 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.
There are multiple common names for Static Factory Methods, some of them are:
Read more about this topic from our resource below.
- Effective Java, 3rd Edition, by Joshua Bloch - Buy from Amazon .