1.这是我自己总结出来的,结合比较器。
如果函数有多个策略实现,可以用策略接口进行封装 ,如果函数有n个策略实现,那我们就创建n个继承策略接口的类,然后再进行重写。
例如:吃饭函数,可以用筷子吃,也可以用勺子吃,如果前期选择用筷子吃策略,后期想用勺子策略吃,就只能将筷子策略注释掉进行重写了,又或者前期引入if else 语句,但会导致不好维护。
java
// 1. 定义策略接口
public interface Fun {
public void function();
}
// 2. 具体策略实现
public class FunA implements Fun {
public void function() {
System.out.println("FunA具体实现");
}
}
public class FunB implements Fun {
public void function() {
System.out.println("FunB具体实现");
}
}
// 3. 上下文类使用策略
public class Main {
public static void test(Fun f) { // 接收接口类型,多态的体现
f.function();
}
public static void main(String[] args) {
test(new FunB()); // 使用策略B
test(new FunA()); // 使用策略A
}
}
2.更完整的例子:排序策略
java
// 策略接口
interface SortStrategy {
void sort(int[] array);
}
// 具体策略
class BubbleSort implements SortStrategy {
public void sort(int[] array) {
System.out.println("使用冒泡排序");
// 实现冒泡排序算法
}
}
class QuickSort implements SortStrategy {
public void sort(int[] array) {
System.out.println("使用快速排序");
// 实现快速排序算法
}
}
class MergeSort implements SortStrategy {
public void sort(int[] array) {
System.out.println("使用归并排序");
// 实现归并排序算法
}
}
// 上下文类
class Sorter {
private SortStrategy strategy;
public void setStrategy(SortStrategy strategy) {
this.strategy = strategy;
}
public void executeSort(int[] array) {
strategy.sort(array);
}
}
// 使用
public class Main {
public static void main(String[] args) {
Sorter sorter = new Sorter();
int[] data = {5, 2, 8, 1, 9};
// 动态切换策略
sorter.setStrategy(new BubbleSort());
sorter.executeSort(data);
sorter.setStrategy(new QuickSort());
sorter.executeSort(data);
}
}