gpt4 book ai didi

java - 使用工厂方法理解 JDBC 等服务提供者框架背后的概念

转载 作者:行者123 更新时间:2023-12-02 01:09:36 25 4
gpt4 key购买 nike

来自Effective Java (第 1 项:考虑静态工厂方法而不是构造函数):

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.

我特别不明白为什么书上说静态工厂方法返回的对象的类在编写包含该方法的类时甚至不需要存在?有人可以用 JDBC 为例解释一下吗?

最佳答案

考虑如下内容:

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);
}
}
}

使用此代码,您的图书馆不需要了解服务的实现。您的库的用户必须设置一个系统属性,其中包含他们想要使用的实现的名称。

这就是你不明白的那句话的意思:工厂方法将返回某个类的实例(该类的名称存储在系统属性“MyServiceImplementation”中),但它完全不知道它是什么类是。它只知道它实现了 MyService 并且它必须有一个公共(public)的、无参数的构造函数(否则,上面的工厂将抛出一个 Error)。

关于java - 使用工厂方法理解 JDBC 等服务提供者框架背后的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32543052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com