zoukankan      html  css  js  c++  java
  • strategytheory.cs

      using System;
     
      // Strategy Pattern    by  Judith Bishop         Oct 2007
      // Shows two strategies and a random switch between them

      // The Context
      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();
        }
      }
     
      // 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 ;
        }
      }
     
      // Client
      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();
        }
      }
      /* Output
      4  || 5  6  7  || 6  || 7  8  9  10  || 9  8  7  6  || 7  || 6  5  
      */
  • 相关阅读:
    【Office】Word排版
    小猪的压力
    SQL SERVER 自定义函数参数数量对调用时参数数量的影响
    工作效率
    C#使用SharpZipLib编辑zip包中内容
    SQL SERVER——自定义函数
    C#字符串编码
    在ASP.NET中启动SQL SERVER缓存
    C#延迟加载
    C#格式化DateTime时间
  • 原文地址:https://www.cnblogs.com/shihao/p/2506821.html
Copyright © 2011-2022 走看看