來源:淘系技術公衆号
作者:之葉

什麼是模闆模式
模闆模式(Template Pattern) 又叫模闆方法模式,其定義了操作的流程,并将流程中的某些步驟延遲到子類中進行實作,使得子類在不改變操作流程的前提下,即可重新定義該操作的某些特定步驟。例如做菜,操作流程一般為 “準備菜”->“放油”->“炒菜”->“調味”->“裝盤”,但可能對于不同的菜要放不同類型的油,不同的菜調味方式也可能不一樣。
何時使用模闆模式
當一個操作的流程較為複雜,可分為多個步驟,且對于不同的操作實作類,流程步驟相同,隻有部分特定步驟才需要自定義,此時可以考慮使用模闆模式。如果一個操作不複雜(即隻有一個步驟),或者不存在相同的流程,那麼應該使用政策模式。從這也可看出模闆模式和政策模式的差別:政策模式關注的是多種政策(廣度),而模闆模式隻關注同種政策(相同流程),但是具備多個步驟,且特定步驟可自定義(深度)。
愉快地使用模闆模式
▐ 背景
我們平台的動态表單在配置表單項的過程中,每新增一個表單項,都要根據表單項的元件類型(例如 單行文本框、下拉選擇框)和目前輸入的各種配置來轉換好對應的 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<FormItemRule> rules = new ArrayList<>(2);
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<FormItemRule> rules = createRules(config);
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<FormItemRule> createRules(FormItemConfig config) {
List<FormItemRule> rules = new ArrayList<>(4);
if (config.isRequired()) {
FormItemRule requiredRule = new FormItemRule();
requiredRule.setRequired(true);
requiredRule.setMessage("請輸入" + config.getTitle());
rules.add(requiredRule);
}
return rules;
}
/**
* 限制規則建立完成之後,子類如果需要特殊處理,可覆寫該方法
*/
protected void afterRulesCreate(List<FormItemRule> rules, FormItemConfig config) { }
}
- 模闆的實作
針對不同的表單項,對特殊步驟進行自定義處理:
/**
* 下拉選擇框的轉換器
*/
@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<FormItemRule> rules, FormItemConfig config) {
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<FormItemTypeEnum, FormItemConverter> CONVERTER_MAP = new EnumMap<>(FormItemTypeEnum.class);
/**
* 根據表單項類型獲得對應的轉換器
*
* @param type 表單項類型
* @return 表單項轉換器
*/
public FormItemConverter getConverter(FormItemTypeEnum type) {
return CONVERTER_MAP.get(type);
}
@Autowired
public void setConverters(List<FormItemConverter> converters) {
for (final FormItemConverter converter : converters) {
CONVERTER_MAP.put(converter.getType(), converter);
}
}
}
- 投入使用
@Component
public class FormItemManagerImpl implements FormItemManager {
@Autowired
private FormItemConverterFactory converterFactory;
@Override
public List<FormItem> convertFormItems(JSONArray inputConfigs) {
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<FormItemRule> rules, FormItemConfig config) {
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 的關聯關系 —— 完美符合 “開閉原則”。
作者|之葉
編輯|橙子君
出品|阿裡巴巴新零售淘系技術