结合工厂模式演进策略模式
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package top.fjy8018.designpattern.pattern.behavior.strategy;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 空策略
|
||||
*
|
||||
* @author F嘉阳
|
||||
* @date 2020/3/4 16:16
|
||||
*/
|
||||
@Slf4j
|
||||
public class EmptyPromotionStrategy implements PromotionStrategy {
|
||||
@Override
|
||||
public void doPromotion() {
|
||||
log.info("空促销策略");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package top.fjy8018.designpattern.pattern.behavior.strategy;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 促销策略工厂
|
||||
*
|
||||
* @author F嘉阳
|
||||
* @date 2020/3/4 16:09
|
||||
*/
|
||||
public class PromotionStrategyFactory {
|
||||
|
||||
private static Map<String, PromotionStrategy> STRATEGY_MAP = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 无促销
|
||||
*/
|
||||
private static final PromotionStrategy NON_PROMOTION = new EmptyPromotionStrategy();
|
||||
|
||||
static {
|
||||
STRATEGY_MAP.put(PromotionKey.FANXIAN, new FanXianPromotionStrategy());
|
||||
STRATEGY_MAP.put(PromotionKey.MANJIAN, new ManJianPromotionStrategy());
|
||||
STRATEGY_MAP.put(PromotionKey.LIJIAN, new LiJianPromotionStrategy());
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁止实例化
|
||||
*/
|
||||
private PromotionStrategyFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 开放获取策略的方法
|
||||
*
|
||||
* @param promotionKey
|
||||
* @return
|
||||
*/
|
||||
public static PromotionStrategy getPromotionStrategy(String promotionKey) {
|
||||
PromotionStrategy strategy = STRATEGY_MAP.get(promotionKey);
|
||||
return strategy == null ? NON_PROMOTION : strategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 常量定义
|
||||
*/
|
||||
private interface PromotionKey {
|
||||
String LIJIAN = "LIJIAN";
|
||||
String FANXIAN = "FANXIAN";
|
||||
String MANJIAN = "MANJIAN";
|
||||
}
|
||||
}
|
||||
@@ -24,4 +24,11 @@ class PromotionStrategyTest {
|
||||
|
||||
activity.executePromotionStrategy();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonIfElse() {
|
||||
String promotionKey = "LIJIAN";
|
||||
PromotionActivity activity = new PromotionActivity(PromotionStrategyFactory.getPromotionStrategy(promotionKey));
|
||||
activity.executePromotionStrategy();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user