# 以促销活动需求为例

## 需求

• 满减，满400减20
• 代金卷，玛莎拉蒂5元代金卷
• 折扣，9折，8折
• 每满减，每满200减10
• 等等

## 简单实现

```public class OrderPromotion {
public BigDecimal promotion(Order order, int[] promotions){
for (int promotion:promotions){
switch (promotion){
case 1:
//计算该类型折扣后的价格
break;
case 2:
//计算该类型折扣后的价格
break;
case 3:
//计算该类型折扣后的价格
break;
//....
}
}
return order.getResultPrice();
}
}```

## 优化一：单一职责原则

```public class OrderPromotion {
public BigDecimal promotion(Order order, int[] promotions){
for (int promotion:promotions){
switch (promotion){
case 1:
calculate1(order);
break;
case 2:
calculate2(order);
break;
case 3:
calculate3(order);
break;
//more promotion
}
}
return order.getResultPrice();
}
public void calculate1(Order order){
//计算使用折扣一后的价格
}
public void calculate2(Order order){
//计算使用折扣二后的价格
}
public void calculate3(Order order){
//计算使用折扣三后的价格
}
//more calculate
}```

## 策略模式

```public class OrderPromotion {
public BigDecimal promotion(Order order, int[] promotions){
for (int promotion:promotions){
switch (promotion){
case 1:
new PromotionType1Calculate(order);
break;
case 2:
new PromotionType1Calculate(order);
break;
case 3:
new PromotionType1Calculate(order);
break;
//more promotion
}
}
return order.getResultPrice();
}
}```

## 优化三：工厂模式

OrderPromotion

```public class OrderPromotion {
public BigDecimal promotion(Order order, int[] promotions){
for (int promotion:promotions){
PromotionFactory.getPromotionCalculate(promotion).calculate(order);
}
return order.getResultPrice();
}
}```

PromotionFactory

```public class PromotionFactory {
public static PromotionCalculate getPromotionCalculate(int promotion){
switch (promotion){
case 1:
return new PromotionType1Calculate(order);
break;
case 2:
return new PromotionType1Calculate(order);
break;
case 3:
return new PromotionType1Calculate(order);
break;
//more promotion
}
return null;
}
}```

## 优化四：配置+反射

mapping.properties

```1=design.order.PromotionType1Calculate
2=design.order.PromotionType2Calculate
3=design.order.PromotionType3Calculate```

PromotionFactory

```public class PromotionFactory {
private static Map<Integer, String> mapping = new HashMap<Integer, String>();
static {
try {
Properties pps = new Properties();
Iterator<String> iterator = pps.stringPropertyNames().iterator();
while(iterator.hasNext()){
String key=iterator.next();
mapping.put(Integer.valueOf(key), pps.getProperty(key));
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static PromotionCalculate getPromotionCalculate(int promotion) throws Exception {
if(mapping.containsKey(promotion)){
String beanName = mapping.get(promotion);
return Class.forName(beanName).newInstance();
}
return null;
}
}```

84 篇文章16 人订阅

0 条评论