简单来说,什么是工厂?

2024-02-29

什么是工厂?我为什么要使用工厂?


你熟悉吗JDBC https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html?这是一个完整的(抽象)工厂。这是一个很好的现实世界例子。

// Factory method. Loads the driver by given classname. It actually returns a 
// concrete Class<Driver>. However, we don't need it here, so we just ignore it.
// It can be any driver class name. The MySQL one here is just an example.
// Under the covers, it will do DriverManager.registerDriver(new Driver()).
Class.forName("com.mysql.jdbc.Driver");

// Abstract factory. This lets the driver return a concrete connection for the
// given URL. You can just declare it against java.sql.Connection interface.
// Under the covers, the DriverManager will find the MySQL driver by URL and call
// driver.connect() which in turn will return new ConnectionImpl().
Connection connection = DriverManager.getConnection(url);

// Abstract factory. This lets the driver return a concrete statement from the
// connection. You can just declare it against java.sql.Statement interface.
// Under the covers, the MySQL ConnectionImpl will return new StatementImpl().
Statement statement = connection.createStatement();

// Abstract factory. This lets the driver return a concrete result set from the
// statement. You can just declare it against java.sql.ResultSet interface.
// Under the covers, the MySQL StatementImpl will return new ResultSetImpl().
ResultSet resultSet = statement.executeQuery(sql);

您不需要任何特定于 JDBC 驱动程序的行import在你的代码中。你不需要做import com.mysql.jdbc.ConnectionImpl或者其他的东西。你只需要声明一切反对java.sql.*。你不需要做connection = new ConnectionImpl();你自己。您只需从抽象工厂获取它作为标准 API 的一部分。

如果您将 JDBC 驱动程序类名设置为可以在外部配置的变量(例如属性文件)并编写 ANSI 兼容的 SQL 查询,那么您就不需要为每个数据库供应商重写、重新编译、重建和重新分发您的 Java 应用程序,并且/或世界都知道的 JDBC 驱动程序。您只需将所需的 JDBC 驱动程序 JAR 文件放入运行时类路径中,并通过某些(属性)文件提供配置,而无需在您想要切换数据库或在不同数据库上重用应用程序时更改任何 Java 代码行。

这就是接口和抽象工厂的力量。

另一个已知的现实示例是 Java EE。将“JDBC”替换为“Java EE”,将“JDBC 驱动程序”替换为“Java EE 应用程序服务器”(WildFly、TomEE、GlassFish、Liberty 等)。

也可以看看:

  • 具体怎么做Class#forName() and DriverManager#getConnection() work? https://stackoverflow.com/questions/2092659/what-is-difference-between-class-forname-and-class-forname-newinstance/2093236#2093236
  • Java EE 到底是什么? https://stackoverflow.com/questions/7295096/what-exactly-is-java-ee
  • 维基百科:工厂方法模式 https://en.wikipedia.org/wiki/Factory_method_pattern
  • 维基百科:抽象工厂模式 https://en.wikipedia.org/wiki/Abstract_factory_pattern
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

简单来说,什么是工厂? 的相关文章

随机推荐