泊而至远

导航

 

定义:是对算法的包装,把使用算法的的责任和算法本身分割开,委派给不同的对象管理,策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类型的子类型、就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换”;

意图:针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以互相替换。策略模式使得算法可以在不影响到客户端的情况下发生变化;

 1 public class StrategyDemo{
 2     public static void main(String []args){
 3         int[] array={1,30,64,88,12,56,28};
 4         ISort bubbleSort=new BubbleSort();
 5         Context con=new Context(bubbleSort);
 6         con.sort(array);
 7         con.printArray(array);
 8     }
 9 }
10 
11 class Context{
12     private ISort iSort=null;
13     public Context(ISort iSort)
14     {
15         this.iSort=iSort;
16     }
17     
18     public void sort(int[] array){
19         //交给具体的策略类对象来帮忙
20         iSort.sort(array);
21     }
22     //打印数组中的内容
23     public void printArray(int[] array){
24         for(int i=0;i<array.length;i++)
25         {
26             System.out.print(array[i]+" ");
27         }
28     }
29 }
30 
31 interface ISort{
32     public void sort(int[] array);
33 }
34 
35 //封装了冒泡排序法
36 class BubbleSort implements ISort{
37     public void sort(int[] array){
38         System.out.println("冒泡排序法");
39         for(int i=0;i<array.length-1;i++){
40             for(int j=0;j<array.length-1-i;j++){
41                 if(array[j]>array[j+1]){
42                     int temp=array[j];
43                     array[j]=array[j+1];
44                     array[j+1]=temp;
45                 }
46             }
47         }
48     }
49 }
50 
51 //封装了选择排序法
52 class SelectSort implements ISort{
53     public void sort(int[] array){
54         System.out.println("选择排序法");
55         int min=0;
56         for(int i=0;i<array.length;i++){
57             min=i;
58             for(int j=i+1;j<array.length;j++){
59                 if(array[min]>array[j]){
60                     min=j;
61                 }
62             }
63             if(i!=min){
64                 int temp=array[i];
65                 array[i]=array[min];
66                 array[min]=temp;
67             }
68         }
69     }
70 }

 

posted on 2016-03-20 21:34  积_跬步  阅读(237)  评论(0编辑  收藏  举报