作者:京東工業(yè) 孫磊
一、概念
策略模式(Strategy Pattern)也稱為(Policy Parttern)。 它定義了算法家族,分別封裝起來,讓它們之間可以互相替換,此模式讓算法的變換,不會影響到使用算法的客戶。策略模式屬性行為模式。
二、實際應(yīng)用
業(yè)務(wù)場景:業(yè)務(wù)需要監(jiān)聽多種消息,將接收到的消息更新到同一個ES中,不同的消息類型使用不同的策略處理,補充不同的數(shù)據(jù)信息,更新到ES中,供商家搜索和統(tǒng)計使用。
代碼實現(xiàn)結(jié)合spring框架、簡單工廠和策略模式一起使用。
public interface GatherExecuteService {
/**
* 處理消息體
*
* @param gatherDataVo
*/
boolean execute(GatherDataVo gatherDataVo);
}
多個實現(xiàn)類
// 價格策略實現(xiàn)
@Service
public class PriceExecuteServiceImpl implements GatherExecuteService {
@Override
public boolean execute(GatherDataVo gatherDataVo) {
.....具體實現(xiàn)代碼省略
}
}
// 商品策略實現(xiàn) @Service public class ProductExecuteServiceImpl implements GatherExecuteService { @Override public boolean execute(GatherDataVo gatherDataVo) { .....具體實現(xiàn)代碼省略 } }
// 庫存策略實現(xiàn)
@Service
public class StockExecuteServiceImpl implements GatherExecuteService {
@Override
public boolean execute(GatherDataVo gatherDataVo) {
.....具體實現(xiàn)代碼省略
}
}
使用枚舉存儲策略實現(xiàn)bean
@Getter
@AllArgsConstructor
public enum MessageTypeEnum {
PRODUCT(0, "productExecuteServiceImpl", "商品基本信息消息"),
PRICE(1, "priceExecuteServiceImpl", "價格消息"),
STOCK(2, "stockExecuteServiceImpl", "庫存消息") ;
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,達到執(zhí)行不同策略的目的。 String serviceName = MessageTypeEnum.getServiceName(gatherDataVo.getMessageType()); if (StringUtils.isNotBlank(serviceName)) { GatherExecuteService gatherExecuteService = (GatherExecuteService) SpringContextUtil.getBean(serviceName, GatherExecuteService.class); }
策略模式是一種比較簡單的設(shè)計模式,工作中經(jīng)常和其他設(shè)計模式一塊使用。簡單的應(yīng)用記錄分享一下。
審核編輯 黃宇
-
代碼
+關(guān)注
關(guān)注
30文章
4940瀏覽量
73069
發(fā)布評論請先 登錄
一文詳解前端常用設(shè)計模式
關(guān)于LVOOP設(shè)計模式的框架問題?
封裝變化與面向接口編程
設(shè)計模式最佳實踐探索—策略模式
為什么我不再推薦枚舉策略模式?
基于輸入阻抗控制的多模式混合PFC的控制策略
如何通過策略模式簡化if-else

設(shè)計模式-策略模式
評論