Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the concept behind Service provider framework like JDBC using the factory method

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 .

like image 845
Geek Avatar asked Aug 06 '12 06:08

Geek


People also ask

What is service provider framework?

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.

What is service provider in Java?

From Java documentation: A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself.


2 Answers

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).

like image 122
Bruno Reis Avatar answered Sep 18 '22 15:09

Bruno Reis


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

like image 26
srikanth yaradla Avatar answered Sep 22 '22 15:09

srikanth yaradla