本文節選自《設計模式就該這樣學》
1 建造者模式的鏈式寫法
以構建一門課程為例,一個完整的課程由PPT課件、回放視訊、課堂筆記、課後作業組成,但是這些內容的設定順序可以隨意調整,我們用建造者模式來代入理解一下。首先建立一個產品類Course。
@Data
public class Course {
private String name;
private String ppt;
private String video;
private String note;
private String homework;
@Override
public String toString() {
return "CourseBuilder{" +
"name='" + name + '\'' +
", ppt='" + ppt + '\'' +
", video='" + video + '\'' +
", note='" + note + '\'' +
", homework='" + homework + '\'' +
'}';
}
}
然後建立建造者類CourseBuilder,將複雜的建立過程封裝起來,建立步驟由使用者決定。
public class CourseBuilder {
private Course course = new Course();
public CourseBuilder addName(String name){
course.setName(name);
return this;
}
public CourseBuilder addPpt(String ppt){
course.setPpt(ppt);
return this;
}
public CourseBuilder addVideo(String video){
course.setVideo(video);
return this;
}
public CourseBuilder addNote(String note){
course.setNote(note);
return this;
}
public CourseBuilder addHomework(String homework){
course.setHomework(homework);
return this;
}
public Course builder(){
return course;
}
}
最後編寫客戶端測試程式碼。
public static void main(String[] args) {
CourseBuilder builder = new CourseBuilder()
.addName("設計模式")
.addPPT("【PPT課件】")
.addVideo("【回放視訊】")
.addNote("【課堂筆記】")
.addHomework("【課後作業】");
System.out.println(builder.build());
}
這樣的寫法是不是很眼熟?後面分析建造者模式在框架原始碼中的應用時大家就會明白。再來看一下類圖的變化,如下圖所示。
2 使用靜態內部類實現建造者模式
事實上,在平常的編碼中,我們通常都會忽略物件的複雜性,優先考慮使用工廠模式建立物件,而不是建造者模式。因為工廠模式和建造者模式的作用都是建立一個產品物件,而工廠模式的結構更加簡潔直接(沒有Builder和 Director),因此更常使用。
一般情況下,我們更習慣使用靜態內部類的方式實現建造者模式,即一個產品類內部自動帶有一個具體建造者,由它負責該產品的組裝建立,不再需要Builder和Director,這樣,產品表示與建立之間的聯絡更加緊密,結構更加緊湊,同時使得建造者模式的形式更加簡潔。
如果採用靜態內部類形式實現建造者模式,則前面的案例可以改寫如下。
@Data
public class Course {
private String name;
private String ppt;
private String video;
private String note;
private String homework;
@Override
public String toString() {
return "Course{" +
"name='" + name + '\'' +
", ppt='" + ppt + '\'' +
", video='" + video + '\'' +
", note='" + note + '\'' +
", homework='" + homework + '\'' +
'}';
}
public static class Builder {
private Course course = new Course();
public Builder addName(String name){
course.setName(name);
return this;
}
public Builder addPpt(String ppt){
course.setPpt(ppt);
return this;
}
public Builder addVideo(String video){
course.setVideo(video);
return this;
}
public Builder addNote(String note){
course.setNote(note);
return this;
}
public Builder addHomework(String homework){
course.setHomework(homework);
return this;
}
public Course builder(){
return course;
}
}
}
客戶端測試程式碼如下。
public static void main(String[] args) {
Course course = new Course.Builder()
.addName("設計模式")
.addPpt("【PPT課件】")
.addVideo("【錄播視訊】")
.builder();
System.out.println(course);
}
這樣,程式碼也會看上去更加簡潔,不會讓人感覺到多了一個類。
3 使用建造者模式動態構建SQL語句
下面來看一個實戰案例,這個案例參考了開源框架JPA的SQL構造模式。我們在構造SQL查詢條件的時候,需要根據不同的條件來拼接SQL字串。如果查詢條件複雜,則SQL拼接的過程也會變得非常複雜,從而給程式碼維護帶來非常大的困難。因此,我們用建造者類QueryRuleSqlBuilder將複雜的SQL構造過程進行封裝,用QueryRule物件專門儲存SQL查詢時的條件,最後根據查詢條件,自動生成SQL語句。首先建立QueryRule類,程式碼如下。
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* QueryRule,主要功能用於構造查詢條件
*
* @author Tom
*/
public final class QueryRule implements Serializable
{
private static final long serialVersionUID = 1L;
public static final int ASC_ORDER = 101;
public static final int DESC_ORDER = 102;
public static final int LIKE = 1;
public static final int IN = 2;
public static final int NOTIN = 3;
public static final int BETWEEN = 4;
public static final int EQ = 5;
public static final int NOTEQ = 6;
public static final int GT = 7;
public static final int GE = 8;
public static final int LT = 9;
public static final int LE = 10;
public static final int ISNULL = 11;
public static final int ISNOTNULL = 12;
public static final int ISEMPTY = 13;
public static final int ISNOTEMPTY = 14;
public static final int AND = 201;
public static final int OR = 202;
private List<Rule> ruleList = new ArrayList<Rule>();
private List<QueryRule> queryRuleList = new ArrayList<QueryRule>();
private String propertyName;
private QueryRule() {}
private QueryRule(String propertyName) {
this.propertyName = propertyName;
}
public static QueryRule getInstance() {
return new QueryRule();
}
/**
* 新增升序規則
* @param propertyName
* @return
*/
public QueryRule addAscOrder(String propertyName) {
this.ruleList.add(new Rule(ASC_ORDER, propertyName));
return this;
}
/**
* 新增降序規則
* @param propertyName
* @return
*/
public QueryRule addDescOrder(String propertyName) {
this.ruleList.add(new Rule(DESC_ORDER, propertyName));
return this;
}
public QueryRule andIsNull(String propertyName) {
this.ruleList.add(new Rule(ISNULL, propertyName).setAndOr(AND));
return this;
}
public QueryRule andIsNotNull(String propertyName) {
this.ruleList.add(new Rule(ISNOTNULL, propertyName).setAndOr(AND));
return this;
}
public QueryRule andIsEmpty(String propertyName) {
this.ruleList.add(new Rule(ISEMPTY, propertyName).setAndOr(AND));
return this;
}
public QueryRule andIsNotEmpty(String propertyName) {
this.ruleList.add(new Rule(ISNOTEMPTY, propertyName).setAndOr(AND));
return this;
}
public QueryRule andLike(String propertyName, Object value) {
this.ruleList.add(new Rule(LIKE, propertyName, new Object[] { value }).setAndOr(AND));
return this;
}
public QueryRule andEqual(String propertyName, Object value) {
this.ruleList.add(new Rule(EQ, propertyName, new Object[] { value }).setAndOr(AND));
return this;
}
public QueryRule andBetween(String propertyName, Object... values) {
this.ruleList.add(new Rule(BETWEEN, propertyName, values).setAndOr(AND));
return this;
}
public QueryRule andIn(String propertyName, List<Object> values) {
this.ruleList.add(new Rule(IN, propertyName, new Object[] { values }).setAndOr(AND));
return this;
}
public QueryRule andIn(String propertyName, Object... values) {
this.ruleList.add(new Rule(IN, propertyName, values).setAndOr(AND));
return this;
}
public QueryRule andNotIn(String propertyName, List<Object> values) {
this.ruleList.add(new Rule(NOTIN,
propertyName,
new Object[] { values }).setAndOr(AND));
return this;
}
//此處省略部分程式碼
public List<Rule> getRuleList() {
return this.ruleList;
}
public List<QueryRule> getQueryRuleList() {
return this.queryRuleList;
}
public String getPropertyName() {
return this.propertyName;
}
protected class Rule implements Serializable {
private static final long serialVersionUID = 1L;
private int type; //規則的型別
private String property_name;
private Object[] values;
private int andOr = AND;
public Rule(int paramInt, String paramString) {
this.property_name = paramString;
this.type = paramInt;
}
public Rule(int paramInt, String paramString,
Object[] paramArrayOfObject) {
this.property_name = paramString;
this.values = paramArrayOfObject;
this.type = paramInt;
}
public Rule setAndOr(int andOr){
this.andOr = andOr;
return this;
}
public int getAndOr(){
return this.andOr;
}
public Object[] getValues() {
return this.values;
}
public int getType() {
return this.type;
}
public String getPropertyName() {
return this.property_name;
}
}
}
然後建立QueryRuleSqlBuilder類。
package com.tom.vip.pattern.builder.sql;
/**
* 根據QueryRule自動構建SQL語句
* @author Tom
*
*/
public class QueryRuleSqlBuilder {
private int CURR_INDEX = 0; //記錄引數所在的位置
private List<String> properties; //儲存列名列表
private List<Object> values; //儲存引數值列表
private List<Order> orders; //儲存排序規則列表
private String whereSql = "";
private String orderSql = "";
private Object [] valueArr = new Object[]{};
private Map<Object,Object> valueMap = new HashMap<Object,Object>();
/**
* 獲得查詢條件
* @return
*/
private String getWhereSql(){
return this.whereSql;
}
/**
* 獲得排序條件
* @return
*/
private String getOrderSql(){
return this.orderSql;
}
/**
* 獲得引數值列表
* @return
*/
public Object [] getValues(){
return this.valueArr;
}
/**
* 獲得引數列表
* @return
*/
private Map<Object,Object> getValueMap(){
return this.valueMap;
}
/**
* 建立SQL構造器
* @param queryRule
*/
public QueryRuleSqlBuilder(QueryRule queryRule) {
CURR_INDEX = 0;
properties = new ArrayList<String>();
values = new ArrayList<Object>();
orders = new ArrayList<Order>();
for (QueryRule.Rule rule : queryRule.getRuleList()) {
switch (rule.getType()) {
case QueryRule.BETWEEN:
processBetween(rule);
break;
case QueryRule.EQ:
processEqual(rule);
break;
case QueryRule.LIKE:
processLike(rule);
break;
case QueryRule.NOTEQ:
processNotEqual(rule);
break;
case QueryRule.GT:
processGreaterThen(rule);
break;
case QueryRule.GE:
processGreaterEqual(rule);
break;
case QueryRule.LT:
processLessThen(rule);
break;
case QueryRule.LE:
processLessEqual(rule);
break;
case QueryRule.IN:
processIN(rule);
break;
case QueryRule.NOTIN:
processNotIN(rule);
break;
case QueryRule.ISNULL:
processIsNull(rule);
break;
case QueryRule.ISNOTNULL:
processIsNotNull(rule);
break;
case QueryRule.ISEMPTY:
processIsEmpty(rule);
break;
case QueryRule.ISNOTEMPTY:
processIsNotEmpty(rule);
break;
case QueryRule.ASC_ORDER:
processOrder(rule);
break;
case QueryRule.DESC_ORDER:
processOrder(rule);
break;
default:
throw new IllegalArgumentException("type"+rule.getType()+"not supported.");
}
}
//拼裝where語句
appendWhereSql();
//拼裝排序語句
appendOrderSql();
//拼裝引數值
appendValues();
}
/**
* 去掉order
*
* @param sql
* @return
*/
private String removeOrders(String sql) {
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sql);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "");
}
m.appendTail(sb);
return sb.toString();
}
/**
* 去掉select
*
* @param sql
* @return
*/
private String removeSelect(String sql) {
if(sql.toLowerCase().matches("from\\s+")){
int beginPos = sql.toLowerCase().indexOf("from");
return sql.substring(beginPos);
}else{
return sql;
}
}
/**
* 處理like
* @param rule
*/
private void processLike(QueryRule.Rule rule) {
if (ArrayUtils.isEmpty(rule.getValues())) {
return;
}
Object obj = rule.getValues()[0];
if (obj != null) {
String value = obj.toString();
if (!StringUtils.isEmpty(value)) {
value = value.replace('*', '%');
obj = value;
}
}
add(rule.getAndOr(),rule.getPropertyName(),"like","%"+rule.getValues()[0]+"%");
}
/**
* 處理between
* @param rule
*/
private void processBetween(QueryRule.Rule rule) {
if ((ArrayUtils.isEmpty(rule.getValues()))
|| (rule.getValues().length < 2)) {
return;
}
add(rule.getAndOr(),rule.getPropertyName(),"","between",rule.getValues()[0],"and");
add(0,"","","",rule.getValues()[1],"");
}
//此處省略部分程式碼
/**
* 加入SQL查詢規則佇列
* @param andOr and或者or
* @param key 列名
* @param split 列名與值之間的間隔
* @param value 值
*/
private void add(int andOr,String key,String split ,Object value){
add(andOr,key,split,"",value,"");
}
/**
* 加入SQL查詢規則佇列
* @param andOr and或者or
* @param key 列名
* @param split 列名與值之間的間隔
* @param prefix 值字首
* @param value 值
* @param suffix 值字尾
*/
private void add(int andOr,String key,String split ,String prefix,Object value,String suffix){
String andOrStr = (0 == andOr ? "" :(QueryRule.AND == andOr ? " and " : " or "));
properties.add(CURR_INDEX,
andOrStr + key + " " + split + prefix + (null != value ? " ? " : " ") + suffix);
if(null != value){
values.add(CURR_INDEX,value);
CURR_INDEX ++;
}
}
/**
* 拼裝where語句
*/
private void appendWhereSql(){
StringBuffer whereSql = new StringBuffer();
for (String p : properties) {
whereSql.append(p);
}
this.whereSql = removeSelect(removeOrders(whereSql.toString()));
}
/**
* 拼裝排序語句
*/
private void appendOrderSql(){
StringBuffer orderSql = new StringBuffer();
for (int i = 0 ; i < orders.size(); i ++) {
if(i > 0 && i < orders.size()){
orderSql.append(",");
}
orderSql.append(orders.get(i).toString());
}
this.orderSql = removeSelect(removeOrders(orderSql.toString()));
}
/**
* 拼裝引數值
*/
private void appendValues(){
Object [] val = new Object[values.size()];
for (int i = 0; i < values.size(); i ++) {
val[i] = values.get(i);
valueMap.put(i, values.get(i));
}
this.valueArr = val;
}
public String builder(String tableName){
String ws = removeFirstAnd(this.getWhereSql());
String whereSql = ("".equals(ws) ? ws : (" where " + ws));
String sql = "select * from " + tableName + whereSql;
Object [] values = this.getValues();
String orderSql = this.getOrderSql();
orderSql = (StringUtils.isEmpty(orderSql) ? " " : (" order by " + orderSql));
sql += orderSql;
return sql;
}
private String removeFirstAnd(String sql){
if(StringUtils.isEmpty(sql)){return sql;}
return sql.trim().toLowerCase().replaceAll("^\\s*and", "") + " ";
}
}
接著建立Order類。
/**
* SQL排序元件
* @author Tom
*/
public class Order {
private boolean ascending; //升序還是降序
private String propertyName; //哪個欄位升序,哪個欄位降序
public String toString() {
return propertyName + ' ' + (ascending ? "asc" : "desc");
}
/**
* Constructor for Order.
*/
protected Order(String propertyName, boolean ascending) {
this.propertyName = propertyName;
this.ascending = ascending;
}
/**
* Ascending order
*
* @param propertyName
* @return Order
*/
public static Order asc(String propertyName) {
return new Order(propertyName, true);
}
/**
* Descending order
*
* @param propertyName
* @return Order
*/
public static Order desc(String propertyName) {
return new Order(propertyName, false);
}
}
最後編寫客戶端測試程式碼。
public static void main(String[] args) {
QueryRule queryRule = QueryRule.getInstance();
queryRule.addAscOrder("age");
queryRule.andEqual("addr","Changsha");
queryRule.andLike("name","Tom");
QueryRuleSqlBuilder builder = new QueryRuleSqlBuilder(queryRule);
System.out.println(builder.builder("t_member"));
System.out.println("Params: " + Arrays.toString(builder.getValues()));
}
這樣一來,客戶端程式碼就非常清楚,執行結果如下圖所示。
本文為“Tom彈架構”原創,轉載請註明出處。技術在於分享,我分享我快樂!
如果本文對您有幫助,歡迎關注和點贊;如果您有任何建議也可留言評論或私信,您的支援是我堅持創作的動力。關注微信公眾號『 Tom彈架構 』可獲取更多技術乾貨!