为什么要使用设计模式
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
}
这里我们将折扣类型的判断和计算价格分开,使得promotion(…)方法的代码量大大降低,提升了代码的可读性。面象对象设计6大原则之一:单一职责原则,这篇也推荐大家看下。
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();
}
}
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;
}
}
1=design.order.PromotionType1Calculate
2=design.order.PromotionType2Calculate
3=design.order.PromotionType3Calculate
public class PromotionFactory {
private static Map<Integer, String> mapping = new HashMap<Integer, String>();
static {
try {
Properties pps = new Properties();
pps.load(new FileInputStream("Test.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;
}
}
作者:宁愿呢
来源:www.cnblogs.com/liyus/p/10508681.html
点击「阅读原文」和栈长学更多~
Go to "Discover" > "Top Stories" > "Wow"