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

*爱你&永不变心* 提交于 2019-12-02 15:38:53

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

srikanth yaradla

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!