Question

From Effective Java (Item 1: Consider static factory methods instead of constructors):

The class of the object returned by a static factory method need not even exist at the time the class containing the method is written. Such flexible static factory methods form the basis of service provider frameworks, such as the Java Database Connectivity API (JDBC). A service provider framework is a system in which multiple service providers implement a service, and the system makes the implementations available to its clients, decoupling them from the implementations.

I specifically do not understand why the book is saying that The class of the object returned by a static factory method need not even exist at the time the class containing the method is written ? Can some one explain using JDBC as the example .

Was it helpful?

Solution

Consider something like the following:

public interface MyService {
  void doSomething();
}

public class MyServiceFactory {
  public static MyService getService() {
    try {
      (MyService) Class.forName(System.getProperty("MyServiceImplemetation")).newInstance();
    } catch (Throwable t) {
      throw new Error(t);
    }
  }
}

With this code, your library doesn't need to know about the implementations of the service. Users of your library would have to set a system property containing the name of the implementation they want to use.

This is what is meant by the sentence you don't understand: the factory method will return an instance of some class (which name is stored in the system property "MyServiceImplementation"), but it has absolutely no idea what class it is. All it knows is that it implements MyService and that it must have a public, no-arg constructor (otherwise, the factory above will throw an Error).

OTHER TIPS

the system makes the implementations available to its clients, decoupling them from the implementations

Just to put it in simpler way you don't add any dependencies of these JDBC vendors at compile time. Clients can add their own at runtime

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top