背景
根据不同的折扣政策,计算商品的价格
使用策略模式之前
package com.design.mode.strategy;
public class Origin {
public static void main(String[] args) {
int discountRate = 8;
discount(discountRate);
}
private static void discount(int discountRate) {
if (10 == discountRate) {
System.out.println("衣服不打折");
System.out.println("鞋子不打折");
System.out.println("化妆品不打折");
} else if (9 == discountRate) {
System.out.println("衣服打9折");
System.out.println("鞋子打9折");
System.out.println("化妆品打9打折");
} else if (8 == discountRate) {
System.out.println("衣服打8折");
System.out.println("鞋子打8折");
System.out.println("化妆品打8打折");
}
}
}
缺陷
if else 中包含了大量的折扣业务代码,如果if判断增加,方法中的代码量持续增加,降低了代码可读性和维护性
使用策略模式之后
package com.design.mode.strategy;
import java.security.PrivateKey;
public class Stratetgy {
public interface DiscountStrategy{
public void discount();
}
public static class Discount10Strategy implements DiscountStrategy {
@Override
public void discount() {
System.out.println("衣服不打折");
System.out.println("鞋子不打折");
System.out.println("化妆品不打折");
}
}
public static class Discount9Strategy implements DiscountStrategy{
@Override
public void discount() {
System.out.println("衣服打9折");
System.out.println("鞋子打9折");
System.out.println("化妆品打9打折");
}
}
public static class Discount8Strategy implements DiscountStrategy{
@Override
public void discount() {
System.out.println("衣服打9折");
System.out.println("鞋子打9折");
System.out.println("化妆品打9打折");
}
}
private static void discount(int discountRate) {
DiscountStrategy stratetgy = null;
if (10 == discountRate) {
stratetgy = new Discount10Strategy();
} else if (9 == discountRate) {
stratetgy = new Discount9Strategy();
} else if (8 == discountRate) {
stratetgy = new Discount8Strategy();
}
if (null != stratetgy) {
stratetgy.discount();
}
}
public static void main(String[] args) {
int discountRate = 9;
discount(discountRate);
}
}
优点
不通过的if else中的业务逻辑分别封装再不同的类中,使if else中的代码没有那么臃肿,增强了代码的可阅读性和维护性