Lec8_Strategy-汉语软件设计模式.ppt

  1. 1、本文档共57页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Lecture 8. 策略模式 The Strategy Pattern 本讲内容 策略模式的引入 策略模式理论 使用策略模式进行设计的例子 策略模式的进一步研究 策略模式的引入 【例1】整数排序程序的设计 需求: 设计一个整数排序程序,分别使用如下的不同 的排序算法 Bubble Sort Binary Sort Heap Sort Insertion Sort Quick Sort Bidirectional Bubble Sort Very Fast Sort, and Supper Fast Sort 策略模式的引入 设计1: 使用一个单独的类进行所有的排序 策略模式的引入 Public class Sorting { public static void main(String[ ] args ) { int choice; if (choice ==1) { bubbleSort (nums); } else if (choice ==2) { quickSort (nums); } //… } public int[] bubbleSort (int[] nums) {// code} public int[] binarySort (int[] nums) {// code} public int[] heapSort (int[] nums) {// code} public int[] insertionSort (int[] nums) {// code} public int[] quickSort (int[] nums) {// code} public int[] bidirectionBubbleSort (int[] nums) {// code} public int[] veryFastSort (int[] nums) {// code} public int[] supperFastSort (int[] nums) {// code} } //the code works, but it has some problems 策略模式的引入 缺点: 当一个新算法被加入到类中, 整个类需要重新编译 当修改某算法的时候,整个类需要重新编译 问题: 怎样改善该设计? 策略模式的引入 策略模式的引入 策略模式的引入 public class SortingAlgorithms{ bubbleSort (int[] nums) {//code } binarySort (int[] nums) {//code } heapSort (int[] nums) {//code } insertionSort (int[] nums) {//code } quickSort (int[] nums) {//code } bidirectionBubbleSort (int[] nums) {//code} veryFastSort (int[] nums) {//code} supperFastSort (int[] nums) {//code} } // Now this design is better, but still not good enough! 策略模式的引入 设计2的优点: 当一个新的算法被添加到类 SortingAlgorithms, 中的时候,类Sorting不需要重新编译(假如在主程序,新算法暂时不需要使用) 策略模式的引入 设计2的缺点: 当增加一个新的算法的时候, 类SortingAlgorithms 仍然需要重新编译 当一个算法被修改的时候, 类SortingAlgorithms 也需要被重新编译 策略模式的引入 问题:能否进一步改进设计的可扩展性? 策略模式的引入 设计3. 我们进一步将类SortingAlgorithms拆分成8个 子类与一个超类的层次类,设计如下: 策略模式的引入 本设计的优点 当新算法被添加的时候,Client类与Sorting类不需要重新编译 当某个算法被修改的时候,Client类与Sorting类不需要重新编译 以上的设计3实际上是使用了策略模式的思想 参与者 Strategy 声明对所支持的算法的共同接口 Context使用这些接口调用定义在某ConcreteStrategy中的算法. ConcreteStrategy 实现Strategy接口定义的算法 Context 被配置一个ConcreteStrategy对象; 维持了一个Strategy对象的引用; 可能定义了接口,使得Strat

文档评论(0)

东山书苑 + 关注
实名认证
内容提供者

业务以学生学习成长为中心,为外语培训、中小学基础教育、学前教育,提供各种学习资料支持服务。

1亿VIP精品文档

相关文档