一、什么是策略设计模式?
- 封装一个类的行为或其算法,使其在运行时可以更改
二、为什么要使用策略设计模式?
- 一种很简单的解释,在我们的开发过程中,经常会遇到大量的if…else或者switch…case语句,当这些语句在开发中只是为了起到分流作用,这些分流和业务逻辑无关,那么这个时候就可以考虑用策略模式。
三、如何实现策略设计模式?
-
我们通过一个demo来演示策略模式。
-
1、比如说: 我们要对猫和狗进行排序。
// 猫和狗对象类。 public class Cat{ int weight, height; public Cat(int weight, int height) { this.weight = weight; this.height = height; } @Override public String toString() { return "Cat{" + "weight=" + weight + ", height=" + height + '}'; } public class Dog { int food; public Dog(int food) { this.food = food; } @Override public String toString() { return "Dog{" + "food=" + food + '}'; } }
-
2、参考上面的代码,我们要对猫进行排序,可能按照
weight
或者height
进行排序。对狗进行排序时,只能按照food
进行排序了。// 设计一个接口 public interface Comparator<T> { int compare(T o1, T o2); } // 实现一个比较策略,比如说对猫进行排序。 // 按照weight进行排序。 public class CatWeightComparator 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 1; } } // 按照height进行排序。 public class CatHeightComparator implements Comparator<Cat>{ @Override public int compare(Cat o1, Cat o2) { if (o1.height > o2.height) return -1; else if (o1.height < o2.height) return 1; else return 1; } } // 对狗进行排序时。同时具体化一个比较策略。 public class DogFoodComparator 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 1; } } // 还得有一个具体的排序的算法 public class Sorter<T> { public void sort2(T[] arr, Comparator<T> comparator) { for (int i = 0; i < arr.length; 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); } } public void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // 测试代码 public class Main { public static void main(String[] args) { Cat[] cats = {new Cat(1, 3), new Cat(2, 2), new Cat(3, 1)}; Dog[] a = {new Dog(3), new Dog(2), new Dog(5)}; Sorter<Cat> sorter2 = new Sorter<>(); sorter2.sort2(cats, new CatHeightComparator()); System.out.println(Arrays.toString(cats)); sorter2.sort2(cats, new CatWeightComparator()); System.out.println(Arrays.toString(cats)); } } // 打印出来的结果根据你传进去的时候使用的是什么一个比较策略,得出来对应的一个结果。 [Cat{weight=1, height=3}, Cat{weight=2, height=2}, Cat{weight=3, height=1}] [Cat{weight=3, height=1}, Cat{weight=2, height=2}, Cat{weight=1, height=3}]