大话设计模式笔记(二)——商品促销 策略模式

  • 2019 年 10 月 30 日
  • 笔记

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/76542977

第二章商品促销——策略模式

需求:商品价格计算,并增加折扣条件

工厂模式UML图

在工厂模式中,调用端代码会通过折扣工厂类生成折扣对象,折扣对象调用折扣方法。这里关联了两个类,工厂类和抽象折扣类。

策略模式UML图

在策略模式中,会在策略环境类的构造器中完成折扣类的初始话,并在策略环境的实现方法调用折扣类的折扣算法。这样调用类只会关联策略环境类。

简单工厂模式需要的是生成的对象,所以在客户端代码中会存在工厂类和生成类,而策略模式关注的是相应算法,它并不关注算法类对象,所以在客户端代码中只会存在context环境类。这样降低代码耦合度。

代码

Context

public class SaleContext {        private SaleStrategy saleStrategy = null;        public SaleContext(String saleSelector) {          switch (saleSelector) {              case "打9折":                  this.saleStrategy = new PercentSaleStrategy(0.9);                  break;              case "打8折":                  this.saleStrategy = new PercentSaleStrategy(0.8);                  break;              case "满300减100":                  this.saleStrategy = new FullSendSaleStrategy(300, 100);                  break;              default:                  this.saleStrategy = new NormalStrategy();                  break;          }      }        public double contextInterface(double money) {          return saleStrategy.getSaleMoney(money);      }    }

SaleStrategy

abstract class SaleStrategy {      public abstract double getSaleMoney(double money);  }

PercentSaleStrategy(折扣促销)

class PercentSaleStrategy extends SaleStrategy {        private double pecent = 0.0d;        public PercentSaleStrategy(double pecent) {          this.pecent = pecent;      }        @Override      public double getSaleMoney(double money) {          return money * pecent;      }  }

FullSendSaleStrategy(满减促销)

class FullSendSaleStrategy extends SaleStrategy {        private double fullMoney = 0.0d;      private double sendMonty = 0.0d;        public FullSendSaleStrategy(double fullMoney, double sendMonty) {          this.fullMoney = fullMoney;          this.sendMonty = sendMonty;      }        @Override      public double getSaleMoney(double money) {          return money > fullMoney ? (money - sendMonty) : money;      }  }

总结

策略模式是定义了一系列算法,这些算法从层次上实现相同的功能,最好析取出算法层,可以减少算法之间和调用算法的耦合。

在实际工作中,当听到需求中包含在不同时间应用不同业务规则,就可以考虑使用策略模式。

设计模式的核心思想就是对接口编程,封装变化。

应用场景

只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式。