策略模式(strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
理念:封装变化点,在不同时间应用不同的业务规则。
如:商场中促销,打折,返利,积分,都是一种促销模式,针对这些促销,可以指定对应的策略。

策略模式设计图

image.png

场景:
针对商场中不同的促销产生不同的策略image.png
使用策略+简单工厂实现
java代码实现

  1. //主函数
  2. public class StrategyTest {
  3. public static void main(String[] args) {
  4. double money = 400;
  5. //正常收费
  6. CashContext context = new CashContext("正常收费");
  7. System.out.println("正常收费:" + context.getResult(money));
  8. //打折
  9. context = new CashContext("打折");
  10. System.out.println("正常收费:" + context.getResult(money));
  11. //返利
  12. context = new CashContext("返利");
  13. System.out.println("正常收费:" + context.getResult(money));
  14. }
  15. }
  16. //现金上下文(类似工厂作用)
  17. public class CashContext {
  18. CashSuper cashSuper;
  19. public CashContext(String type) {
  20. switch (type) {
  21. case "正常收费":
  22. cashSuper = new CashNormal();
  23. break;
  24. case "打折":
  25. cashSuper = new CashRebate(0.8);
  26. break;
  27. case "返利":
  28. cashSuper = new CashReturn(300, 100);
  29. break;
  30. }
  31. }
  32. public double getResult(double money) {
  33. return cashSuper.acceptCash(money);
  34. }
  35. }
  36. //策略的抽象类
  37. public abstract class CashSuper {
  38. public abstract double acceptCash(double money);
  39. }
  40. //正常收费策略
  41. public class CashNormal extends CashSuper {
  42. @Override
  43. public double acceptCash(double money) {
  44. return money;
  45. }
  46. }
  47. //打折收费策略
  48. public class CashRebate extends CashSuper {
  49. public double discount;
  50. public CashRebate(double discount) {
  51. this.discount = discount;
  52. }
  53. @Override
  54. public double acceptCash(double money) {
  55. return money * discount;
  56. }
  57. }
  58. //返利收费策略
  59. public class CashReturn extends CashSuper {
  60. public double moneyCondition = 0.0;
  61. public double moneyReturn = 0.0;
  62. public CashReturn(double moneyCondition, double moneyReturn){
  63. this.moneyCondition = moneyCondition;
  64. this.moneyReturn = moneyReturn;
  65. }
  66. @Override
  67. public double acceptCash(double money) {
  68. double result = money;
  69. if (money > moneyCondition){
  70. result = result - (int)(money / moneyCondition) * moneyReturn;
  71. }
  72. return result;
  73. }
  74. }

存在的问题,如果新增促销策略,需要在工厂的switch里添加代码,可以使用反射优化