java連線池出現javax.naming.NameNotFoundException: Name jdbc is not bound in this Context 或者出現 java.sql.S
阿新 • • 發佈:2020-12-10
技術標籤:架構及效能調優
定義
策略模式是對演算法的包裝,把使用演算法的責任和演算法本身分隔開,委派給不同的物件管理。策略模式通常把一系列的演算法包裝 到一系列的策略類裡面,作為一個抽象策略類的子類。
優點
1、演算法可以自由切換。
2、避免使用多重條件判斷。
3、擴充套件性良好。
缺點
1、策略類會增多。
2、所有策略類都需要對外暴露。
案例
結算價格計算,根據Vip不同等級進行運算
使用者在購買商品的時候,很多時候會根據Vip等級打不同折扣,這裡也基於真實電商案例來實現VIP等級價格制:
Vip0->普通價格
Vip1->減5元
Vip2->7折
Vip3->5折
實現
定義策略介面: Strategy
public interface Strategy {
//價格計算
Integer payMoney(Integer payMoney);
}
定義Vip0策略: StrategyVipOne
@Component(value = "strategyVipOne") public class StrategyVipOne implements Strategy { //普通會員,沒有優惠 @Override public Integer payMoney(Integer payMoney) { return payMoney; } }
定義Vip1策略: StrategyVipTwo
@Component(value = "strategyVipTwo")
public class StrategyVipTwo implements Strategy{
//策略2
@Override
public Integer payMoney(Integer payMoney) {
return payMoney-5;
}
}
定義Vip2策略: StrategyVipThree
@Component(value = "strategyVipThree") public class StrategyVipThree implements Strategy{ //策略3 @Override public Integer payMoney(Integer payMoney) { return (int)(payMoney*0.7); } }
定義Vip3策略: StrategyVipFour(參照上方,省略)
定義策略工廠: StrategyFactory
@Data
@ConfigurationProperties(prefix = "strategy")
@Component public class StrategyFactory implements ApplicationContextAware{
//ApplicationContext
//1、定義一個Map儲存所有策略【strategyVipOne=instanceOne】
// 【strategyVipTwo=instanceTwo】
private ApplicationContext act;
//定義一個Map,儲存等級和策略的關係,通過application.yml配置注入進來
private Map<Integer,String> strategyMap;
//3、根據會員等級獲取策略【1】【2】【3】
public Strategy getStrategy(Integer level){
//根據等級獲取策略ID
String id = strategyMap.get(level);
//根據ID獲取對應例項
return act.getBean(id,Strategy.class);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
act=applicationContext;
}
}
等級策略配置:修改application.yml,將如下策略配置進去
#策略配置
strategy:
strategyMap:
1: strategyVipOne
2: strategyVipTwo
3: strategyVipThree
4: strategyVipFour
可根據實際使用者等級欄位獲取到不同的策略實現類執行payMoney