定义
建造者模式就是在一个对象在创建的过程中动态的为对象的属性赋值,比如在创建一条sql语句的时候会添加很多不同的条件,不同的sql语句会有不同的条件
public class BuildTest {
public static void main(String[] args) {
MysqlCommand command = MysqlCommand.build("aa","table")
.andEquals("id","1")
.andEquals("user_id","2")
.andNotEquals("m","1");
command.insert();
}
}
class MysqlCommand{
String dbName;
String tableName;
public static MysqlCommand build(String dbName, String tableName ){
System.out.println("连接数据库 : " +dbName );
return new MysqlCommand(dbName,tableName);
}
public MysqlCommand(String dbName, String tableName) {
this.dbName = dbName;
this.tableName = tableName;
}
private Map<String,String> equalsMap = new HashMap<>();
private Map<String,String> notEqualsMap =new HashMap<>();
public MysqlCommand andEquals(String key, String value){
equalsMap.put(key,value);
return this;
}
public MysqlCommand andNotEquals(String key, String value){
notEqualsMap.put(key,value);
return this;
}
public void insert(){
System.out.println("执行 insert 命令");
excute("instert into " + tableName);
}
private void excute(String sql){
System.out.println(sql);
System.out.println("相当条件 :" +sqlEqCondition()) ;
System.out.println("不相等条件 :" +sqlNotEqCondition());
}
String sqlEqCondition(){
String cdt = "";
for (Map.Entry<String, String> entry : equalsMap.entrySet()) {
cdt += entry.getKey() + " = " + entry.getValue() + " , ";
}
return cdt;
}
String sqlNotEqCondition(){
String cdt = "";
for (Map.Entry<String, String> entry : notEqualsMap.entrySet()) {
cdt += entry.getKey() + " != " + entry.getValue() + " , ";
}
return cdt;
}
}
使用建造者模式构建动态SQL语句
这篇博客介绍了建造者模式在构建动态SQL语句中的应用。通过MysqlCommand类的静态方法build开始,逐步添加各种条件(如等于、不等于),最终形成完整的SQL插入语句。该模式允许在运行时动态组合条件,提高了代码的灵活性和可读性。
330

被折叠的 条评论
为什么被折叠?



