zoukankan      html  css  js  c++  java
  • 设计模式之五(策略模式)

    前言

    策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。

    策略模式结构图

     

    Strategy:策略类,定义所有支持的算法的公共接口

    ConcreteStrategy1,ConcreteStrategy2,ConcreteStrategy3这三个是具体策略类,封装了具体的算法或行为,继承于Strategy

    Context上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。

    代码实现

    简单了解了一下,策略模式的定义和它的模式结构图之后,我们现在通过代码进行进一步的了解。

    Strategy类,定义所有支持的算法的公共接口

        public abstract  class Strategy
        {
            public abstract void AlgorithmInterface();
        }

    ConcreteStrategy,封装了具体的算法或行为,继承于Strategy

     
        public class ConcreteStrategy1 : Strategy
        {
            public override void AlgorithmInterface()
            {
                Console.WriteLine("算法1的实现");
            }
        }
    
        public class ConcreteStrategy2 : Strategy
        {
            public override void AlgorithmInterface()
            {
                Console.WriteLine("算法2的实现");
            }
        }
    
        public class ConcreteStrategy3 : Strategy
        {
            public override void AlgorithmInterface()
            {
                Console.WriteLine("算法3的实现");
            }
        }

    Context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。

        public class Context
        {
            Strategy strategy;
            public Context(Strategy strategy)
            {
                this.strategy = strategy;
            }
    
            public void ContextInterface()
            {
                strategy.AlgorithmInterface();
            }
        }

    客户端调用代码

        class Program
        {
            static void Main(string[] args)
            {
                Context context;
    
                context = new Context(new ConcreteStrategy1());
                context.ContextInterface();
    
                context = new Context(new ConcreteStrategy2());
                context.ContextInterface();
    
                context = new Context(new ConcreteStrategy3());
                context.ContextInterface();
    
                Console.ReadLine();
            }
        }

    运行效果展示

    总结

     策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。

    策略模式的优点:

      策略模式的Strategy类层次为Context定义了一系列可供重用的算法或行为。继承有助于析取出这些算法的公共功能。

      简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。

    总的来说,策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。

  • 相关阅读:
    嵌入式实验一:LED灯点亮
    [转] sql中的in与not in,exists与not exists的区别
    订单管理系统基本情况
    solaris系统分区及格式化
    百度超大网盘邀请码,点击可以获得额外的300M哦
    vb设置代理ip
    我看到一种防伪查询系统,叫做西门防伪防伪查询系统,不知道好不好用。
    零碎知识点整理
    初学WCF之消息模式3——双工模式
    HTTP 错误 500.21 Internal Server Error
  • 原文地址:https://www.cnblogs.com/aehyok/p/3105324.html
Copyright © 2011-2022 走看看