博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式之五(策略模式)
阅读量:4569 次
发布时间:2019-06-08

本文共 2077 字,大约阅读时间需要 6 分钟。

原文:

前言

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

策略模式结构图

 

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定义了一系列可供重用的算法或行为。继承有助于析取出这些算法的公共功能。

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

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

 

 

posted on
2014-03-18 23:11 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/lonelyxmas/p/3608998.html

你可能感兴趣的文章
python小白-day5 time&datetime模块
查看>>
使用c++实现一个FTP客户端(三)
查看>>
ffmpeg 转换VC工具已经可以生成工程文件(续)
查看>>
OpenGL + C++ + Java
查看>>
UOJ #15 虫洞路线
查看>>
一些较好的书
查看>>
绑定一个值给radio
查看>>
友晶Sdram_Control_4Port的全页操作Bug?
查看>>
用MVC5+EF6+WebApi 做一个小功能(一)开场挖坑,在线答题系统
查看>>
box-shadow详解
查看>>
线段树——HYSBZ - 3224
查看>>
EF6+SQLite3数据库出现类型转换失败的问题(指定的转换无效)
查看>>
谷歌希望让 Swift 成为安卓的优先选择,以取代由 Oracle 开发的 Java 程序语言。...
查看>>
Windsock套接字I/O模型学习 --- 第一章
查看>>
浏览器兼容问题笔记
查看>>
OUTLOOK+VBA 备份邮件到GMAIL
查看>>
谁说delphi没有IOCP库,delphi新的IOCP类库,开源中: DIOCP组件JSON流模块说明
查看>>
[四种方法]检测数据类型
查看>>
chrome使用技巧 值得珍藏
查看>>
【IT笔试面试题整理】数组中出现次数超过一半的数字
查看>>