策略模式:我们会创建表示各种策略的对象和一个行为随着策略对象改变而改变的context对象,策略对象改变context对象的执行算法。
策略模式简单的理解就是:策略模式封装的是做一件事的不同方式。
举例:现在我们要对数组中的元素进行排序,要求能满足各种类型的数组都可以排序,int,double,long,甚至是cat,student,dog等。传统的做法可能是针对每一种类型的数组都写出一个方法,然后对应的数组调用对应的方法进行排序。
但是当我们完成这些时,我们会发现其实每一个方法都大同小异,排序的方式(冒泡,快排,选择等等)都是一样,只不过比较的属性不同罢了,一些是数组位置上的元素可以直接进行比较来排序,有一些是数组位置上的元素的某些属性来比较排序。所以归根结底我们做的事只有一件,就是排序,不同的只是比较的内容不同而已。所以这里我们可以使用策略模式来完成这件事。
首先我们先一个Comparator接口
public interface Comparator<T> { int compare(T o1,T o2); }
然后我们写一个Cat类
public class Cat { int weight,height; public Cat(int weight,int height){ this.height = height; this.weight = weight; } @Override public String toString() { return "Cat{" + "weight=" + weight + ", height=" + height + '}'; } }
再写一个Dog类
public class Dog { int food; public Dog(int food){ this.food = food; } @Override public String toString() { return "Dog{" + "food=" + food + '}'; } }
然后再写一个CatComparator类来实现Comparator接口中的compare方法,这里你就可以随意定义需要比较的属性是什么。
public class CatComparator implements Comparator<Cat> { @Override public int compare(Cat o1, Cat o2) { if (o1.weight<o2.weight) return -1; else if (o1.weight>o2.weight) return 1; else return 0; } }
然后再写一个DogComparator类来实现Comparator接口中的compare方法
public class DogComparator implements Comparator<Dog> { @Override public int compare(Dog o1, Dog o2) { if (o1.food<o2.food) return -1; else if (o1.food>o2.food) return 1; else return 0; } }
然后再写一个Sorter类完成排序
public class Sorter<T> { public void sort(T[] arr, Comparator<T> comparator) { for(int i=0; i<arr.length - 1; i++) { int minPos = i; for(int j=i+1; j<arr.length; j++) { minPos = comparator.compare(arr[j],arr[minPos])==-1 ? j : minPos; } swap(arr, i, minPos); } } void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
然后再在Main方法中调用
import java.util.Arrays; public class Main { public static void main(String[] args) { Dog[] a = {new Dog(2),new Dog(1),new Dog(5)}; Cat[] b = {new Cat(3,3),new Cat(2,2),new Cat(1,1)}; Sorter<Dog> sorter1 = new Sorter<>(); Sorter<Cat> sorter2 = new Sorter<>(); sorter1.sort(a,new DogComparator()); sorter2.sort(b,new CatComparator()); System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(b)); } }
我们可以看一下结果:
这里就是使用了策略模式。当然这里也可以直接在Cat和Dog中直接实现 Comparator接口,实现其中的campare方法。
策略模式是Java多态的体现,在设计模式中属于行为型模式。