设计模式(七) 策略模式

策略模式是一种定义一系列算法的方法,以相同的方式调用不同的算法,减少了各种算法类与使用算法类之间的耦合。
它的重心不是如何实现算法,而是如何组织,调用这些算法。从而让程序结构更灵活,具有更好的维护性和扩展性。
代码实现:
//算法策略接口
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 );

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

posted @ 2020-12-07 21:45  唐磊(Jason)  阅读(76)  评论(0编辑  收藏  举报