设计模式-12-策略模式
来源:互联网 发布:网络打印机 编辑:程序博客网 时间:2024/06/04 19:39
策略模式:一个类的行为或其算法可以在运行时更改。
策略模式就是对这段代码的改进
public void selectSort(String type){ if("type1".equals(type)){ //选择快速排序 } else if("type2".equals(type)){ //选择插入排序 } else if("type3".equals(type)){ //选择冒泡排序 } else if("type4".equals(type)){ //选择选择排序 } ...... }
接口
public interface Sort{ public abstract int[] sort(int arr[]);}
相应的策略
//冒泡排序public class BubbleSort implements Sort{ public int[] sort(int arr[]){ int len=arr.length; for(int i=0;i<len;i++){ for(int j=i+1;j<len;j++){ int temp; if(arr[i]>arr[j]){ temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } } System.out.println("冒泡排序"); return arr; }}
//插入排序public class InsertionSort implements Sort { public int[] sort(int arr[]) { int len = arr.length; for (int i = 1; i < len; i++) { int j; int temp = arr[i]; for (j = i; j > 0; j--) { if (arr[j - 1] > temp) { arr[j] = arr[j - 1]; } else break; } arr[j] = temp; } System.out.println("插入排序"); return arr; }}
//选择排序public class SelectionSort implements Sort { public int[] sort(int arr[]) { int len = arr.length; int temp; for (int i = 0; i < len; i++) { temp = arr[i]; int j; int samllestLocation = i; for (j = i + 1; j < len; j++) { if (arr[j] < temp) { temp = arr[j]; samllestLocation = j; } } arr[samllestLocation] = arr[i]; arr[i] = temp; } System.out.println("选择排序"); return arr; }}
实例化策略的时候选择相应的排序,相当于if中的条件
public class ArrayHandler{ private Sort sortObj; public int[] sort(int arr[]) { sortObj.sort(arr); return arr; } public void setSortObj(Sort sortObj) { this.sortObj = sortObj; }}
测试
public class Client{ public static void main(String args[]) { int arr[]={1,4,6,2,5,3,7,10,9}; int result[]; ArrayHandler ah=new ArrayHandler(); Sort sort = new SelectionSort(); //使用选择排序 ah.setSortObj(sort); //设置具体策略 result=ah.sort(arr); for(int i=0;i<result.length;i++) { System.out.print(result[i] + ","); } }}
阅读全文
0 0
- 设计模式12:策略模式
- 设计模式-12-策略模式
- 设计模式12-策略模式
- 设计模式-策略模式
- 设计模式:策略模式
- 设计模式-策略模式
- 设计模式 - 策略模式
- 设计模式-策略模式
- 设计模式-----策略模式
- 设计模式 策略模式
- 设计模式-策略模式
- 设计模式-【策略模式】
- 设计模式-----策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- 设计模式- 策略模式
- 设计模式- 策略模式
- 设计模式------策略模式
- 如何在SpringBoot下读取自定义properties配置文件
- Maximum Sequence
- JDE正式表数据迁移到中间表
- JavaEE开发第二篇Spring-Aop
- 利用第三方API服务实现归属地查询
- 设计模式-12-策略模式
- Struts2 Action
- vue-cli脚手架 webpack中引入jquery
- 机器学习之感知机与SVM详细推导
- UVA11799 Horror Dash【求极值+水题】
- solr学习(6.1)solrcloud集群的搭建
- 开发技能-shell面试整理
- 【剑指offer】面试题34:二叉树中和为某一值的路径
- Regular polygon