设计模式(七) 策略模式

策略模式是一种定义一系列算法的方法,以相同的方式调用不同的算法,减少了各种算法类与使用算法类之间的耦合。
它的重心不是如何实现算法,而是如何组织,调用这些算法。从而让程序结构更灵活,具有更好的维护性和扩展性。
代码实现:
复制代码
//算法策略接口
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 @   唐磊(Jason)  阅读(80)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示