乐趣区

关于设计模式:设计模式策略模式

策略模式: 定义一组算法,将每个算法都封装起来,并且使他们之间能够调换

简略点了解为定义公共办法, 调用公共办法

public class Person {
    private int age;
    private int num;

    public Person(int age, int name) {
        this.age = age;
        this.num = name;
    }

    public int getAge() {return age;}

    public void setAge(int age) {this.age = age;}

    public int getNum() {return num;}

    public void setNum(int name) {this.num = name;}
}
// 定义公共办法
@FunctionalInterface
public interface Comparator<T> {int compareTo(T o1,T o2);
}
// 调用时应用接口
public class Sorter<T> {public void sort(T[] arr, Comparator<T> comparator) {
        // 冒泡排序
        for (int i = 0; i < arr.length - 1; i++) {
            int pos = i;
            for (int j = i + 1; j < arr.length; j++) {pos = comparator.compareTo(arr[j], arr[pos]) == -1 ? j : pos;
            }
            swap(arr, i, pos);
        }
    }

    void swap(T[] arr, int i, int j) {T temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
//main 办法, 对于不同策略只须要实现 comparator 接口就行
public class Main {public static void main(String[] args) {Person[] arr = {new Person(20, 3), new Person(19, 1), new Person(21, 2)};
        Sorter<Person> sorter = new Sorter<>();
        // 按年龄排序
        sorter.sort(arr, (o1, o2) -> {if (o1.getAge() > o2.getAge()) {return 1;} else if (o1.getAge() < o2.getAge()) {return -1;} else {return 0;}
        });
        // 按 num 排序
        sorter.sort(arr, (o1, o2) -> {if (o1.getNum() > o2.getNum()) {return 1;} else if (o1.getNum() < o2.getNum()) {return -1;} else {return 0;}
        });
        // 由此可见, 策略模式能够随便扩大, 只有实现对应接口就行
    }
}
退出移动版