While reading "Effective Java" J.Bloch came across this statement
A fifth advantage of static factories is that the class of the returned object need not exist when the class containing the method is written.
What does it mean? Can someone explain it with some examples ?
The static factory methods are methods that return an instance of the native class. The static factory method has names that clarify the code, unlike the constructors. In the static factory method, we do not need to create a new object upon each invocation i.e object can be cached and reused if required.
A factory method is nothing but a static method that returns an object of the class. The most common example of a factory method is getInstance() method of any Singleton class, which many of you have already used.
It means that the API of your static factory method can return an interface type, of which the implementation won't be written or generated until later.
As an example:
public static MyInterface getMyInterfaceInstance() {
//load instance dynamically and return it.
}
In this case, the factory method only needs the MyInterface
interface to exist when it's being compiled. The actual implementation can be loaded dynamically at runtime in many ways, including:
In particular, the last two options simply mean that the implementation class can be written in a different module (and many modules can provide an implementation of the interface), and these implementation classes will be discovered at runtime - which makes it possible for the static factory method to be written before the actual implementation class.
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