代码改变世界

策略模式

  Clingingboy  阅读(411)  评论(0编辑  收藏  举报

     此模式意图在于切换算法,其实现方式与模板模式,桥接模式等是大同小异,或者可以说是相同,只有意图不同而已.初学设计模式都被这相似的代码,不同的模式搞混乱了。其实仅仅就是抽象而已。

image_2

1.接口与实现

// Strategy interface
 interface IStrategy  {
   int Move (Context c);
 }
 
 // Strategy 1
 class Strategy1 : IStrategy {
   public int Move (Context c) {
     return ++c.Counter;
   }
 }
 
 // Strategy 2
 class Strategy2 : IStrategy {
   public int Move (Context c) {
     return --c.Counter ;
   }
 }

2.上下文的一个类

class Context {
   // Context state
   public const int start = 5;
   public int Counter = 5;
   
   // Strategy aggregation
   IStrategy strategy = new Strategy1();
   
   // Algorithm invokes a strategy method
   public int Algorithm() {
     return strategy.Move(this);
   }
   
   // Changing strategies
   public void SwitchStrategy() {
     if (strategy is Strategy1)
       strategy = new Strategy2();
     else 
       strategy = new Strategy1();
   }
 }

3.客户端调用

static class Program {
   static void Main () {
     Context context = new Context();
     context.SwitchStrategy();
     Random r = new Random(37);
     for (int i=Context.start; i<=Context.start+15; i++) {
       if (r.Next(3) == 2) {
         Console.Write("|| ");
         context.SwitchStrategy();
       }
       Console.Write(context.Algorithm() +"  ");
     }
     Console.WriteLine();
     Console.ReadKey();
   }
 }

其实就是这么简单.当然还有很多变态体,知道其是干什么就可以了
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2009-08-26 Spring.NET学习笔记(6)-基础AOP
点击右上角即可分享
微信分享提示