zoukankan      html  css  js  c++  java
  • 策略模式

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

    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();
       }
     }

    其实就是这么简单.当然还有很多变态体,知道其是干什么就可以了
  • 相关阅读:
    数据的追踪审计
    通知模块设计
    数据库'tempdb' 的事务日志已满处理方法
    三级联动
    组合查询
    用户控件
    MDI容器
    控件说明
    winfrom
    自动生成编号
  • 原文地址:https://www.cnblogs.com/Clingingboy/p/1809552.html
Copyright © 2011-2022 走看看