设计模式-建造者模式
建造者模式是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
用户只需要指定需要建造的类型就可以获得对象,建造过程和细节不需要了解。
例子:
package com.black.design.pattern.builder.sql;
import java.util.ArrayList;
import java.util.List;
// 查询规则类
public class QueryRule {
// 查询条件
private List<String> conditions = new ArrayList<String>();
// 排序字段
private List<String> orderConditions = new ArrayList<String>();
// 参数值
private List<Object> params = new ArrayList<Object>();
public QueryRule addAscOrder(String propertyName) {
orderConditions.add(propertyName + " asc");
return this;
}
public QueryRule addDescOrder(String propertyName, Object v) {
orderConditions.add(propertyName + " desc");
return this;
}
public QueryRule andLike(String propertyName, Object v) {
params.add("%"+v+"%");
conditions.add(propertyName + " like ");
return this;
}
public QueryRule andEquals(String propertyName, Object v) {
params.add(v);
conditions.add(propertyName + " = ");
return this;
}
public QueryRule andGreaterEquals(String propertyName, Object v) {
params.add(v);
conditions.add(propertyName + " >= ");
return this;
}
public List<String> getConditions() {
return conditions;
}
public List<String> getOrderConditions() {
return orderConditions;
}
public List<Object> getParams() {
return params;
}
}
package com.black.design.pattern.builder.sql;
import java.util.ArrayList;
import java.util.List;
// sql 构造器
public class QueryRuleSqlBuilder {
private QueryRule queryRule;
private List<Object> values = new ArrayList<Object>();
public QueryRuleSqlBuilder(QueryRule queryRule) {
this.queryRule = queryRule;
this.values = queryRule.getParams();
}
public String build(String tableName) {
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("select * from ").append(tableName);
List<String> conditions = queryRule.getConditions();
for (int i = 0; i < conditions.size(); i++) {
if(i==0) {
sqlBuffer.append(" where ");
}
sqlBuffer.append(conditions.get(i)).append("?");
if(i < conditions.size() - 1) {
sqlBuffer.append(" and ");
}
}
//排序
List<String> orders = queryRule.getOrderConditions();
for (int i = 0; i < orders.size(); i++) {
if(i==0) {
sqlBuffer.append(" order by ");
}
sqlBuffer.append(orders.get(i));
if(i < orders.size() - 1) {
sqlBuffer.append(",");
}
}
sqlBuffer.append(";");
return sqlBuffer.toString();
}
public List<Object> getValues() {
return values;
}
}
测试:
package com.black.design.pattern.builder.sql;
public class QueryRuleSqlBuilderTest {
public static void main(String[] args) {
QueryRule queryRule = new QueryRule();
queryRule.addAscOrder("age");
queryRule.andEquals("addr", "北京市");
queryRule.andLike("name", "black");
queryRule.andGreaterEquals("age", 18);
queryRule.andGreaterEquals("time", "2021-01-01");
QueryRuleSqlBuilder builder = new QueryRuleSqlBuilder(queryRule);
System.out.println(builder.build("t_user"));
System.out.println(builder.getValues());
}
}
输出:
select * from t_user where addr = ? and name like ? and age >= ? and time >= ? order by age asc;
[北京市, %black%, 18, 2021-01-01]