Reputation: 519
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 ?
Upvotes: 12
Views: 1376
Reputation: 45329
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.
Upvotes: 8