关于java:策略模式

23次阅读

共计 1612 个字符,预计需要花费 5 分钟才能阅读完成。

1 概念

工厂模式是解耦对象的创立和应用,观察者模式是解耦观察者和被观察者。策略模式跟两者相似,也能起到解耦的作用,不过,它 == 解耦的是策略的定义、创立、应用这三局部 ==

2 实现

这里实现一个计算订单价格的策略,商品可能会做各种流动,每种流动折扣都不一样,这里通过策略模式实现,代码简洁,当前减少流动的时候不须要批改原有代码。

2.1 策略接口定义

/**
 * 策略定义
 *
 * @Author: prepared
 * @Date: 2021/6/21 15:04
 */
public interface DiscountStrategy {double calDiscount(Order order);
}

2.2 具体策略实现

GrouponDiscountStrategy、PromotionDiscountStrategy 具体实现都统一,这里就不写了。

@Service
public class NormalDiscountStrategy implements PushStrategyI{private Logger logger = LoggerFactory.getLogger(NormalDiscountStrategy.class);

    @Override
    public Response calDiscount(Long userId) {}}

2.3 策略工厂

这里也能够将具体的策略通过属性注入进来,获取策略的办法,通过 if/else 判断获取对应的策略。

/**
 * 应用工厂模式 创立策略
 *
 * @Author: prepared
 * @Date: 2021/6/21 15:04
 */
public class DiscountStrategyFactory {private static final Map<OrderType, DiscountStrategy> strategies = new HashMap<>();

    static {strategies.put(OrderType.NORMAL, new NormalDiscountStrategy());
        strategies.put(OrderType.GROUPON, new GrouponDiscountStrategy());
        strategies.put(OrderType.PROMOTION, new PromotionDiscountStrategy());
    }

    public static DiscountStrategy getDiscountStrategy(OrderType type) {return strategies.get(type);
    }
}

2.4 策略的应用

/**
 * 策略的应用
 *
 * @Author: prepared
 * @Date: 2021/6/21 15:04
 */
public class OrderService {public double discount(Order order) {OrderType type = order.getType();
        DiscountStrategy discountStrategy = DiscountStrategyFactory.getDiscountStrategy(type);
        return discountStrategy.calDiscount(order);
    }

}

3 利用场景

最常见的利用场景是,利用它来防止简短的 if-else 或 switch 分支判断。策略模式实用于依据不同类型的动静,决定应用哪种策略这样一种利用场景。

策略模式次要的作用还是解耦策略的定义、创立和应用,控制代码的复杂度,让每个局部都不至于过于简单、代码量过多。

4 理论应用场景

商城推广的时候,有的需要是给用户发短信,有的需要给用户打电话,还有的需要是给用户发送微信告诉音讯或者其余告诉。

在这里应用策略模式,代码简洁,而且不便扩大其余策略,比方当前须要钉钉告诉音讯、用户精准广告等等测试。

否则每次减少需要的时候,都须要大规模批改原有代码,与设计准则【对扩大凋谢,对批改敞开】不符。

正文完
 0