作者:京東工業(yè) 孫磊
一、概念
策略模式(Strategy Pattern)也稱為(Policy Parttern)。 它定義了算法家族,分別封裝起來(lái),讓它們之間可以互相替換,此模式讓算法的變換,不會(huì)影響到使用算法的客戶。策略模式屬性行為模式。
二、實(shí)際應(yīng)用
業(yè)務(wù)場(chǎng)景:業(yè)務(wù)需要監(jiān)聽(tīng)多種消息,將接收到的消息更新到同一個(gè)ES中,不同的消息類型使用不同的策略處理,補(bǔ)充不同的數(shù)據(jù)信息,更新到ES中,供商家搜索和統(tǒng)計(jì)使用。
代碼實(shí)現(xiàn)結(jié)合spring框架、簡(jiǎn)單工廠和策略模式一起使用。
public interface GatherExecuteService { /** * 處理消息體 * * @param gatherDataVo */ boolean execute(GatherDataVo gatherDataVo); }
多個(gè)實(shí)現(xiàn)類
// 價(jià)格策略實(shí)現(xiàn) @Service public class PriceExecuteServiceImpl implements GatherExecuteService { @Override public boolean execute(GatherDataVo gatherDataVo) { .....具體實(shí)現(xiàn)代碼省略 } }
// 商品策略實(shí)現(xiàn) @Service public class ProductExecuteServiceImpl implements GatherExecuteService { @Override public boolean execute(GatherDataVo gatherDataVo) { .....具體實(shí)現(xiàn)代碼省略 } }
// 庫(kù)存策略實(shí)現(xiàn) @Service public class StockExecuteServiceImpl implements GatherExecuteService { @Override public boolean execute(GatherDataVo gatherDataVo) { .....具體實(shí)現(xiàn)代碼省略 } }
使用枚舉存儲(chǔ)策略實(shí)現(xiàn)bean
@Getter @AllArgsConstructor public enum MessageTypeEnum { PRODUCT(0, "productExecuteServiceImpl", "商品基本信息消息"), PRICE(1, "priceExecuteServiceImpl", "價(jià)格消息"), STOCK(2, "stockExecuteServiceImpl", "庫(kù)存消息") ; private int type; private String service; private String description; public static String getServiceName(int type) { MessageTypeEnum[] typeEnums = MessageTypeEnum.values(); for (MessageTypeEnum enumType : typeEnums) { if (enumType.getType() == type) { return enumType.getService(); } } return null; } }
使用到不同策略的代碼
// 根據(jù)消息類型獲取不同策略類,然后使用spring的ApplicationContext獲取bean,達(dá)到執(zhí)行不同策略的目的。 String serviceName = MessageTypeEnum.getServiceName(gatherDataVo.getMessageType()); if (StringUtils.isNotBlank(serviceName)) { GatherExecuteService gatherExecuteService = (GatherExecuteService) SpringContextUtil.getBean(serviceName, GatherExecuteService.class); }
策略模式是一種比較簡(jiǎn)單的設(shè)計(jì)模式,工作中經(jīng)常和其他設(shè)計(jì)模式一塊使用。簡(jiǎn)單的應(yīng)用記錄分享一下。
審核編輯 黃宇
-
代碼
+關(guān)注
關(guān)注
30文章
4893瀏覽量
70441
發(fā)布評(píng)論請(qǐng)先 登錄
一文詳解前端常用設(shè)計(jì)模式

關(guān)于LVOOP設(shè)計(jì)模式的框架問(wèn)題?
封裝變化與面向接口編程

不會(huì)有人不知道怎么優(yōu)雅的替換if-else語(yǔ)句吧

設(shè)計(jì)模式最佳實(shí)踐探索—策略模式
為什么我不再推薦枚舉策略模式?
基于輸入阻抗控制的多模式混合PFC的控制策略

高頻使用的幾種設(shè)計(jì)模式

設(shè)計(jì)模式行為型:策略模式

迭代模式在UVM中的應(yīng)用有哪些

如何通過(guò)策略模式簡(jiǎn)化if-else

評(píng)論