Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Static factories returned object need not exist" mean?

Tags:

java

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 ?

like image 995
gg ff Avatar asked Nov 10 '18 15:11

gg ff


People also ask

What is a static factory?

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.

Are factory methods always static?

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.


1 Answers

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:

  • Creating a proxy object
  • Reflection (configurable implementation class name loaded at runtime)
  • Looking up a service loader

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.

like image 120
ernest_k Avatar answered Sep 24 '22 02:09

ernest_k