可用于创建工厂模式。当创建的对象需要附加的构造函数参数来运行时,通常会使用工厂模式,但每次都提供这些代码很麻烦:
考虑:
public class QueryFactory {
@Inject private Database database;
public Query create(String sql) {
return new Query(database, sql);
}
}
public class Query {
private final Database database;
private final String sql;
public Query(Database database, String sql) {
this.database = database;
this.sql = sql;
}
public List performQuery() {
return database.query(sql);
}
}
用作:
Query q = queryFactory.create("SELECT * FROM employees");
q.performQuery();
使用非静态内部类可以实现相同的目的:
public class QueryFactory {
@Inject private Database database;
public class Query {
private final String sql;
public Query(String sql) {
this.sql = sql;
}
public List performQuery() {
return database.query(sql);
}
}
}
用于:
Query q = queryFactory.new Query("SELECT * FROM employees");
q.performQuery();
工厂从具有特别命名的方法,如受益create
,createFromSQL
或createFromTemplate
。在这里也可以以多个内部类的形式进行相同的操作:
public class QueryFactory {
public class SQL { ... }
public class Native { ... }
public class Builder { ... }
}
从工厂到构造的类传递的参数较少,但是可读性可能会有所下降。
相比:
Queries.Native q = queries.new Native("select * from employees");
与
Query q = queryFactory.createNative("select * from employees");