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

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

结构
意图 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
适用性
  • 许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
  • 需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间/时间权衡的算法。当这些变体实现为一个算法的类层次时[ H O 8 7 ] ,可以使用策略模式。
  • 算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
  • 一个类定义了多种行为, 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的S t r a t e g y 类中以代替这些条件语句。

 

1 using System; 2  3      4     abstract class Strategy  5     { 6         abstract public void DoAlgorithm(); 7     } 8  9     class FirstStrategy : Strategy 10     {11         override public void DoAlgorithm()12         {13             Console.WriteLine("In first strategy");            14         }15     }16 17     class SecondStrategy : Strategy 18     {19         override public void DoAlgorithm()20         {21             Console.WriteLine("In second strategy");            22         }23     }24 25     class Context 26     {27         Strategy s;28         public Context(Strategy strat)29         {30             s = strat;            31         }32 33         public void DoWork()34         {35             // some of the context's own code goes here36         }37 38         public void DoStrategyWork()39         {40             // now we can hand off to the strategy to do some 41             // more work42             s.DoAlgorithm();43         }44     }45 46     /// 47     ///    Summary description for Client.48     /// 49     public class Client50     {51         public static int Main(string[] args)52         {    53             FirstStrategy firstStrategy = new FirstStrategy();54             Context c = new Context(firstStrategy);55             c.DoWork();56             c.DoStrategyWork();57 58             return 0;59         }60     }
策略模式

 

转载于:https://www.cnblogs.com/ziranquliu/p/4653409.html

你可能感兴趣的文章
当人类与机器人一起工作,不是为了简单的提高效率
查看>>
Go Ticker资源泄露案例
查看>>
SVN
查看>>
利用Python来执行可执行jar包。
查看>>
[note]CSS相关(# 和 . 的区别,及CSS常用中文字体英文名称对照表
查看>>
cisco IOS更新
查看>>
mysql导出存储过程或函数
查看>>
mahout 安装
查看>>
【漏洞复现】 CVE-2018-9995 DVR登陆绕过漏洞
查看>>
Using Basemap 1.0.7 in Python 3.6
查看>>
Android禁止自动同步网络时间
查看>>
输入两个时间戳,计算差值
查看>>
对frameset、iframe、frame的js操作
查看>>
UML的9种图
查看>>
4月第2周中国五大顶级域名总量净增4.7万 美国净减4.3万
查看>>
8月第3周全球域名商(国际域名)新增注册量TOP16
查看>>
JS类似PHP的格式化时间
查看>>
解决:找不到或无法加载主类
查看>>
RFC2326(2) RSTP
查看>>
awk的基本使用方法
查看>>