定義
- 封裝了不同的算法吓歇,讓他們可以相互替換,算法的變化不會影響使用算法的用戶
類型:行為型
使用場景
- 系統(tǒng)有很多類惠奸,而他們的區(qū)別在于行為不同
- 一個系統(tǒng)需要動態(tài)的在幾種算法中選擇一種
優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
- 開閉原則
- 避免使用大量的條件轉(zhuǎn)移語句(if...else...)
- 提高算法的保密性和安全性
缺點(diǎn):
- 客戶端必須知道所有的策略類,并自行決定使用哪一個策略類
- 產(chǎn)生很多策略類
策略和工廠模式結(jié)合
public class PromotionStrategyFactory {
private static Map<String, PromotionStrategy> PROMOTION_STRATEGY = new HashMap<String, PromotionStrategy>();
static {
PROMOTION_STRATEGY.put(PromotionKey.MANJIAN, new ManJianPromotionStrategy());
PROMOTION_STRATEGY.put(PromotionKey.LIJIAN, new LiJianPromotionStrategy());
PROMOTION_STRATEGY.put(PromotionKey.FANXIAN, new FanXianPromotionStrategy());
}
private static PromotionStrategy EMPRT_PROMOTION = new EmptyPromotionStrategy();
private PromotionStrategyFactory() {
}
public static PromotionStrategy getPromotionStrategy(String PromotionKey) {
PromotionStrategy promotionStrategy = PROMOTION_STRATEGY.get(PromotionKey);
return promotionStrategy == null ? EMPRT_PROMOTION : promotionStrategy;
}
private interface PromotionKey {
String LIJIAN = "LIJIAN";
String MANJIAN = "MANJIAN";
String FANXIAN = "FANXIAN";
}
}
UML類圖
image.png