zoukankan      html  css  js  c++  java
  • 策略模式

    该模式假定场景为商场打折促销,“正常收费”,“打几折”,“满减”,等活动。

    这个场景中有如下对象:

      选择促销方法对象

      促销方法对象

      结算对象

      

    结构图如上

    代码实现:

     1 public class CashContext
     2     {
     3         CashSuper cs = null;
     4         public CashContext(string type) {
     5             switch (type)
     6             {
     7                 case "正常收费":
     8                     cs = new CashNormal();
     9                     break;
    10                 case "八折":
    11                     CashRebate cr = new CashRebate(0.8);
    12                     cs = cr;
    13                     break;
    14                 case "满300减100":
    15                     cs = new CashReturn(300, 100);
    16                     break;
    17                 default:
    18                     break;
    19             }
    20         }
    21 
    22         /// <summary>
    23         /// 返回核算金额
    24         /// </summary>
    25         /// <param name="money"></param>
    26         /// <returns></returns>
    27         public double GetResult(double money) {
    28             return cs.acceptCash(money);
    29         }
    30     }
    Context
    1 public abstract class CashSuper
    2     {
    3         /// <summary>
    4         /// 核算费用
    5         /// </summary>
    6         /// <param name="money"></param>
    7         /// <returns></returns>
    8         public abstract double acceptCash(double money);
    9     }
    抽象类

    这是简单工厂融合了策略模式的一种实现。在context中通过switch创建不同促销对象,这样的好处在于其他开发人员只了解context就可以了。单纯的使用工厂模式则需要多了解2个类,这也给开发带来的难度

    策略模式是一种定义一系列算法的方法,算法完成的都是相同的工作,只是实现不同。

  • 相关阅读:
    Median Value
    237. Delete Node in a Linked List
    206. Reverse Linked List
    160. Intersection of Two Linked Lists
    83. Remove Duplicates from Sorted List
    21. Merge Two Sorted Lists
    477. Total Hamming Distance
    421. Maximum XOR of Two Numbers in an Array
    397. Integer Replacement
    318. Maximum Product of Word Lengths
  • 原文地址:https://www.cnblogs.com/cuijl/p/8111840.html
Copyright © 2011-2022 走看看