Bal*_*usC 39
你熟悉JDBC吗?它是一个和所有(抽象)工厂.这是一个很好的现实世界的例子.
// 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);
Run Code Online (Sandbox Code Playgroud)
您不需要import在代码中使用一行JDBC驱动程序.你不需要做什么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等).
eab*_*ham 23
在需要在运行时创建对象的多个实例的情况下,Factory设计模式非常理想.您可以初始化许多实例,而不是显式创建每个实例.此外,您可以封装可以多次重用的复杂创建代码.
例:
public class Person {
int ID;
String gender;
public Person(int ID,String gender){
this.ID=ID;
this.gender=gender;
}
public int getID() {
return ID;
}
public String getGender() {
return gender;
}
}
public class PersonFactory{
public static Person createMale(int id){
return new Person(id,"M");
}
public static Person createFemale(int id){
return new Person(id,"F");
}
}
public class factorytest{
public static void main(String[]args){
Person[] pList= new Person[100];
for(int x=0;x<100;x++){
pList[x]=PersonFactory.createMale(x);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我们封装了性别初始化参数的细节,并且可以简单地让PersonFactory创建createMale或createFemale Person对象.
| 归档时间: |
|
| 查看次数: |
18568 次 |
| 最近记录: |