策略模式简答例子

策略模式:

 1 package strategymodetest;
 2 
 3 public class StrategyDemo {
 4 
 5     /**策略模式编程思路:
 6      * 1、定义策略接口,表示具备某种能力,功能
 7      * 2.定义接口实现类,具备具体的功能
 8      * 3.定义使用类,该类持有接口(接口作为该类的一个属性,并使用构造方法为该属性赋值)
 9      * 4.new出接口的实现类,将实现类对象作为参数,再new出一个使用类,
10      * @param args
11      */
12     public static void main(String[] args) {
13         int[] array = {1,56,44,22,11,66,90,80};
14         ISort bubbleSort = new BubbleSort();
15         ISort selectSort = new SelectSort();
16         Context context = new Context(selectSort);
17         context.sort(array);
18         context.printArray(array);    
19     }
20 
21 }
22 
23 class Context {
24     private ISort iSort = null;//Context使用ISort,持有ISort接口的引用变量,可以接收不同的具体的策略类对象
25     public Context(ISort iSort) {
26         this.iSort = iSort;        
27     }
28     public void sort(int[] array) {
29         iSort.sort(array);//交给具体接收到的策略类对象来排序
30     }//父类引用变量调用父类的方法时,调用的是具体的对象重写后的方法;
31     
32     public void printArray(int[] array) {
33         for(int i = 0; i < array.length; i++) {
34             System.out.print(array[i]+ " ");
35         }
36     }
37 }
38 
39 interface ISort {//策略类接口,表示排序功能
40     public void sort(int [] array);
41 }
42 
43 //封装了冒泡排序法 ——具体的排序算法
44 class BubbleSort implements ISort {
45 
46     @Override
47     public void sort(int[] array) {
48         System.out.println("冒泡排序法");//冒泡排序,外循环n-1次,内循环n-i-1次,n是数组长度
49         for(int i = 0; i < array.length - 1; i++) {
50             for(int j = 0; j < array.length - i - 1; j ++) {
51                 if(array[j] > array [j+1]) {
52                     int temp = array[j];
53                     array[j] = array[j+1];
54                     array[j+1] = temp;
55                 }
56             }
57         }        
58     }
59 }
60 
61 //封装选择排序法
62 class SelectSort implements ISort {
63 
64     @Override
65     public void sort(int[] array) {
66         System.out.println("选择排序法");
67         int min = 0;
68         for(int i = 0; i < array.length; i++) {
69             min = i;
70             for(int j= i+1; j <array.length; j++) {
71                 if(array[min] > array[j]) {
72                     min = j;//保存最小的数的下标
73                 }
74             }
75             if(i!=min) {
76                 int temp = array[i];
77                 array[i] = array[min];
78                 array[min] = temp;
79             }
80         }
81     }
82     
83 }

 

posted @ 2018-01-04 11:49  清风拂来  阅读(172)  评论(0编辑  收藏  举报