设计模式-策略模式

时间 2019/3/24 18:20:45 加载中...

场景

老大:

我们的收银台项目要新增一个功能。在结账的时候,可能会打折,打几折都有可能,有的是满几百就减免多少,你来实现下这个功能。

我:

好的

我心想:

说白了,就是对总钱数进行运算得到一个新的结果。只是怎么运算的事情。不同情况下采用不同的运算方式,又可以称不同的策略。

代码如下:

策略接口

  1. package StrategyPattern;
  2. public interface IStrategy {
  3. double cal(Double total);
  4. }

打折策略

  1. package StrategyPattern;
  2. public class StrategyDiscount implements IStrategy {
  3. /*
  4. * 折扣
  5. */
  6. private int discount;
  7. public StrategyDiscount(int discount) {
  8. this.discount = discount;
  9. }
  10. public double cal(Double total) {
  11. return total * discount * 0.01;
  12. }
  13. }

正常无优惠

  1. package StrategyPattern;
  2. public class StrategyNormal implements IStrategy {
  3. public double cal(Double total) {
  4. return total;
  5. }
  6. }

返利

  1. package StrategyPattern;
  2. public class StrategyReturn implements IStrategy {
  3. private double condition;
  4. private double returnNum;
  5. public StrategyReturn(double condition, double returnNum) {
  6. this.condition = condition;
  7. this.returnNum = returnNum;
  8. }
  9. public double cal(Double total) {
  10. if (total >= condition)
  11. return total - Math.floor(total / condition) * returnNum;
  12. else
  13. return total;
  14. }
  15. }

有一个context来决定使用哪个策略

  1. package StrategyPattern;
  2. public class StrategyContext {
  3. private IStrategy strategy;
  4. public StrategyContext(String type) throws Exception {
  5. switch (type) {
  6. case "normal":
  7. strategy = new StrategyNormal();
  8. break;
  9. case "discount":
  10. strategy = new StrategyDiscount(1);
  11. break;
  12. case "return":
  13. strategy = new StrategyReturn(300, 100);
  14. break;
  15. default:
  16. throw new Exception("没有合适的策略");
  17. }
  18. }
  19. public double cal(Double total) {
  20. return strategy.cal(total);
  21. }
  22. }

客户端直接调用 context 即可。

  1. package StrategyPattern;
  2. public class Program {
  3. public static void main(String[] args) throws Exception {
  4. String type = "打折";
  5. double total = 100;
  6. StrategyContext context = new StrategyContext(type);
  7. double result = context.cal(total);
  8. }
  9. }

类图

客户端直接调用 StrategyContext,而其又根据不同的条件采取不同的策略。

扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/strategy-pattern.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。