• 设计模式(七) 策略模式


    策略模式是一种定义一系列算法的方法,以相同的方式调用不同的算法,减少了各种算法类与使用算法类之间的耦合。
    它的重心不是如何实现算法,而是如何组织,调用这些算法。从而让程序结构更灵活,具有更好的维护性和扩展性。
    代码实现:
    //算法策略接口
    public interface IStrategy
    {
         int GetPayment(int charge);
    }
    //策略A
    public class CashNormarl : IStrategy
    {
       public  int GetPayment(int charge)
       {
                   return charge;
       }
    }
    //策略B
    public class CashReturn : IStrategy
    {
       public  int GetPayment(int charge)
       {
                  if(charge >= 300)
                  {
                            return charge-100;
                 }
       }
    }
    //组织策略上下文
    public class CashContext
    {
       IStrategy  _strategy ;
       public CashContext(IStrategy strategy)
       {
                 _strategy = strategy;
       }
       public  int GetPayment(int charge)
       {
                 return   _strategy.GetPayment();
       }
    }
    
    //客户端调用
    int charge = 1000;
    var cash = CashContext(new CashReturn());
    var payment =  cash.GetPayment(charge );
    View Code

    还可以通过简单工厂模式来优化 组织策略上下文类 ,让客户端与算法实现类完全解耦

  • 相关阅读:
    UVaLive 7362 Farey (数学,欧拉函数)
    UVaLive 7361 Immortal Porpoises (矩阵快速幂)
    UVaLive 7359 Sum Kind Of Problem (数学,水题)
    CodeForces 706D Vasiliy's Multiset (字典树查询+贪心)
    负载均衡服务器
    集群-如何理解集群?
    架构规划
    领域模型
    状态图
    E-R图
  • 原文地址:https://www.cnblogs.com/jasonbourne3/p/14099877.html
Copyright © 2020-2023  润新知