简体   繁体   中英

What does “Static factories returned object need not exist” mean?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM