設計模式最佳套路4 —— 愉快地使用模板模式
場景模式怎麼開
本篇為設計模式第三篇,
第一篇可見
設計模式最佳套路1 —— 愉快地使用策略模式
,
第二篇可見
設計模式最佳套路2 —— 基於 Spring 實現管道模式的最佳實踐,
第三篇可見設計模式最佳套路3 —— 愉快地使用代理模式
什麼是模板模式
當一個操作的流程較為複雜,可分為多個步驟,且對於不同的操作實現類,流程步驟相同,只有部分特定步驟才需要自定義,此時可以考慮使用模板模式。如果一個操作不復雜(即只有一個步驟),或者不存在相同的流程,那麼應該使用策略模式。從這也可看出模板模式和策略模式的區別:策略模式關注的是多種策略(廣度),而模板模式只關注同種策略(相同流程),但是具備多個步驟,且特定步驟可自定義(深度)。
愉快地使用模板模式
|
|
背景
我們平臺的動態表單在配置表單項的過程中,每新增一個表單項,都要根據表單項的元件型別(例如 單行文字框、下拉選擇框)和當前輸入的各種配置來轉換好對應的 Schema 並儲存在 DB 中。一開始,轉換的程式碼邏輯大概是這樣的:
public class FormItemConverter {
/**
* 將輸入的配置轉變為表單項
*
* @param config 前端輸入的配置
* @return 表單項
*/
public FormItem convert(FormItemConfig config) {
FormItem formItem = new FormItem();
// 公共的表單項屬性
formItem。setTitle(config。getTitle());
formItem。setCode(config。getCode());
formItem。setComponent(config。getComponent());
// 建立表單元件的屬性
FormComponentProps props = new FormComponentProps();
formItem。setComponentProps(props);
// 公共的元件屬性
if (config。isReadOnly()) {
props。setReadOnly(true);
}
FormItemTypeEnum type = config。getType();
// 下拉選擇框的特殊屬性處理
if (type == ComponentTypeEnum。DROPDOWN_SELECT) {
props。setAutoWidth(false);
if (config。isMultiple()) {
props。setMode(“multiple”);
}
}
// 模糊搜尋框的特殊屬性處理
if (type == ComponentTypeEnum。FUZZY_SEARCH) {
formItem。setFuzzySearch(true);
props。setAutoWidth(false);
}
// 。。。 其他元件的特殊處理
// 建立約束規則
List
formItem。setRules(rules);
// 每個表單項都可有的約束規則
if (config。isRequired()) {
FormItemRule requiredRule = new FormItemRule();
requiredRule。setRequired(true);
requiredRule。setMessage(“請輸入” + config。getTitle());
rules。add(requiredRule);
}
// 文字輸入框才有的規則
if (type == ComponentTypeEnum。TEXT_INPUT || type == ComponentTypeEnum。TEXT_AREA) {
Integer minLength = config。getMinLength();
if (minLength != null && minLength > 0) {
FormItemRule minRule = new FormItemRule();
minRule。setMin(minLength);
minRule。setMessage(“請至少輸入 ” + minLength + “ 個字”);
rules。add(minRule);
}
Integer maxLength = config。getMaxLength();
if (maxLength != null && maxLength > 0) {
FormItemRule maxRule = new FormItemRule();
maxRule。setMax(maxLength);
maxRule。setMessage(“請最多輸入 ” + maxLength + “ 個字”);
rules。add(maxRule);
}
}
// 。。。 其他約束規則
return formItem;
}
}
很明顯,這份程式碼違反了 開閉原則(對擴充套件開放,對修改關閉):如果此時需要新增一種新的表單項(包含特殊的元件屬性),那麼不可避免的要修改 convert 方法來進行新表單項的特殊處理。觀察上面的程式碼,將配置轉變為表單項 這個操作,滿足以下流程:
建立表單項,並設定通用的表單項屬性,然後再對不同表單項的特殊屬性進行處理
建立元件屬性,處理通用的元件屬性,然後再對不同元件的特殊屬性進行處理
建立約束規則,處理通用的約束規則,然後再對不同表單項的特性約束規則進行處理
這不正是符合模板模式的使用場景(操作流程固定,特殊步驟可自定義處理)嗎?基於上面這個場景,下面我就分享一下我目前基於 Spring 實現模板模式的 “最佳套路”(如果你有更好的套路,歡迎賜教和討論哦)~
|
|
方案
|
定義出模板
即首先定義出表單項轉換的操作流程,即如下的 convert 方法(使用 final 修飾,確保子類不可修改操作流程):
public abstract class FormItemConverter {
/**
* 子類可處理的表單項型別
*/
public abstract FormItemTypeEnum getType();
/**
* 將輸入的配置轉變為表單項的操作流程
*
* @param config 前端輸入的配置
* @return 表單項
*/
public final FormItem convert(FormItemConfig config) {
FormItem item = createItem(config);
// 表單項建立完成之後,子類如果需要特殊處理,可覆寫該方法
afterItemCreate(item, config);
FormComponentProps props = createComponentProps(config);
item。setComponentProps(props);
// 元件屬性建立完成之後,子類如果需要特殊處理,可覆寫該方法
afterPropsCreate(props, config);
List
item。setRules(rules);
// 約束規則建立完成之後,子類如果需要特殊處理,可覆寫該方法
afterRulesCreate(rules, config);
return item;
}
/**
* 共用邏輯:建立表單項、設定通用的表單項屬性
*/
private FormItem createItem(FormItemConfig config) {
FormItem formItem = new FormItem();
formItem。setCode(config。getCode());
formItem。setTitle(config。getTitle());
formItem。setComponent(config。getComponent());
return formItem;
}
/**
* 表單項建立完成之後,子類如果需要特殊處理,可覆寫該方法
*/
protected void afterItemCreate(FormItem item, FormItemConfig config) { }
/**
* 共用邏輯:建立元件屬性、設定通用的元件屬性
*/
private FormComponentProps createComponentProps(FormItemConfig config) {
FormComponentProps props = new FormComponentProps();
if (config。isReadOnly()) {
props。setReadOnly(true);
}
if (StringUtils。isNotBlank(config。getPlaceholder())) {
props。setPlaceholder(config。getPlaceholder());
}
return props;
}
/**
* 元件屬性建立完成之後,子類如果需要特殊處理,可覆寫該方法
*/
protected void afterPropsCreate(FormComponentProps props, FormItemConfig config) { }
/**
* 共用邏輯:建立約束規則、設定通用的約束規則
*/
private List
List
if (config。isRequired()) {
FormItemRule requiredRule = new FormItemRule();
requiredRule。setRequired(true);
requiredRule。setMessage(“請輸入” + config。getTitle());
rules。add(requiredRule);
}
return rules;
}
/**
* 約束規則建立完成之後,子類如果需要特殊處理,可覆寫該方法
*/
protected void afterRulesCreate(List
}
|
模板的實現
針對不同的表單項,對特殊步驟進行自定義處理:
/**
* 下拉選擇框的轉換器
*/
@Component
public class DropdownSelectConverter extends FormItemConverter {
@Override
public FormItemTypeEnum getType() {
return FormItemTypeEnum。DROPDOWN_SELECT;
}
@Override
protected void afterPropsCreate(FormComponentProps props, FormItemConfig config) {
props。setAutoWidth(false);
if (config。isMultiple()) {
props。setMode(“multiple”);
}
}
}
/**
* 模糊搜尋框的轉換器
*/
@Component
public class FuzzySearchConverter extends FormItemConverter {
@Override
public FormItemTypeEnum getType() {
return FormItemTypeEnum。FUZZY_SEARCH;
}
@Override
protected void afterItemCreate(FormItem item, FormItemConfig config) {
item。setFuzzySearch(true);
}
@Override
protected void afterPropsCreate(FormComponentProps props, FormItemConfig config) {
props。setAutoWidth(false);
}
}
/**
* 通用文字類轉換器
*/
public abstract class CommonTextConverter extends FormItemConverter {
@Override
protected void afterRulesCreate(List
Integer minLength = config。getMinLength();
if (minLength != null && minLength > 0) {
FormItemRule minRule = new FormItemRule();
minRule。setMin(minLength);
minRule。setMessage(“請至少輸入 ” + minLength + “ 個字”);
rules。add(minRule);
}
Integer maxLength = config。getMaxLength();
if (maxLength != null && maxLength > 0) {
FormItemRule maxRule = new FormItemRule();
maxRule。setMax(maxLength);
maxRule。setMessage(“請最多輸入 ” + maxLength + “ 個字”);
rules。add(maxRule);
}
}
}
/**
* 單行文字框的轉換器
*/
@Component
public class TextInputConverter extends CommonTextConverter {
@Override
public FormItemTypeEnum getType() {
return FormItemTypeEnum。TEXT_INPUT;
}
}
/**
* 多行文字框的轉換器
*/
@Component
public class TextAreaConvertor extends FormItemConverter {
@Override
public FormItemTypeEnum getType() {
return FormItemTypeEnum。TEXT_AREA;
}
}
|
製作簡單工廠
@Component
public class FormItemConverterFactory {
private static final
EnumMap
/**
* 根據表單項型別獲得對應的轉換器
*
* @param type 表單項型別
* @return 表單項轉換器
*/
public FormItemConverter getConverter(FormItemTypeEnum type) {
return CONVERTER_MAP。get(type);
}
@Autowired
public void setConverters(List
for (final FormItemConverter converter : converters) {
CONVERTER_MAP。put(converter。getType(), converter);
}
}
}
投入使用
@Component
public class FormItemManagerImpl implements FormItemManager {
@Autowired
private FormItemConverterFactory converterFactory;
@Override
public List
return IntStream。range(0, inputConfigs。size())
。mapToObj(inputConfigs::getJSONObject)
。map(this::convertFormItem)
。collect(Collectors。toList());
}
private FormItem convertFormItem(JSONObject inputConfig) {
FormItemConfig itemConfig = inputConfig。toJavaObject(FormItemConfig。class);
FormItemConverter converter = converterFactory。getConverter(itemConfig。getType());
if (converter == null) {
throw new IllegalArgumentException(“不存在轉換器:” + itemConfig。getType());
}
return converter。convert(itemConfig);
}
}
Factory 只負責獲取 Converter,每個 Converter 只負責對應表單項的轉換功能,Manager 只負責邏輯編排,從而達到功能上的 “低耦合高內聚”。
| 設想一次擴充套件
此時要加入一種新的表單項 —— 數字選擇器(NUMBER_PICKER),它有著特殊的約束條件:最小值和最大值,輸入到 FormItemConfig 時分別為 minNumer 和 maxNumber。
@Component
public class NumberPickerConverter extends FormItemConverter {
@Override
public FormItemTypeEnum getType() {
return FormItemTypeEnum。NUMBER_PICKER;
}
@Override
protected void afterRulesCreate(List
Integer minNumber = config。getMinNumber();
// 處理最小值
if (minNumber != null) {
FormItemRule minNumRule = new FormItemRule();
minNumRule。setMinimum(minNumber);
minNumRule。setMessage(“輸入數字不能小於 ” + minNumber);
rules。add(minNumRule);
}
Integer maxNumber = config。getMaxNumber();
// 處理最大值
if (maxNumber != null) {
FormItemRule maxNumRule = new FormItemRule();
maxNumRule。setMaximum(maxNumber);
maxNumRule。setMessage(“輸入數字不能大於 ” + maxNumber);
rules。add(maxNumRule);
}
}
}
此時,我們只需要新增對應的列舉和實現對應的 FormItemConverter,並不需要修改任何邏輯程式碼,因為 Spring 啟動時會自動幫我們處理好 NUMBER_PICKER 和 NumberPickerConverter 的關聯關係 —— 完美符合 “開閉原則”。
(本篇內容作者:阿里巴巴淘系技術部 之葉)
————————————————————————————————————————
阿里巴巴集團淘系技術部官方賬號。淘系技術部是阿里巴巴新零售技術的王牌軍,支撐淘寶、天貓核心電商以及淘寶直播、閒魚、躺平、阿里汽車、阿里房產等創新業務,服務9億使用者,賦能各行業1000萬商家。我們打造了全球領先的線上新零售技術平臺,並作為核心技術團隊保障了11次雙十一購物狂歡節的成功。詳情可檢視我們官網:
阿里巴巴淘系技術部官方網站
點選下方主頁關注我們,你將收穫更多來自阿里一線工程師的技術實戰技巧&成長經歷心得。另,不定期更新最新崗位招聘資訊和簡歷內推通道,歡迎各位以最短路徑加入我們。
阿里巴巴淘系技術