設計模式-策略模式

策略模式:定義一組算法,將每一個算法都封裝起來,而且使他們之間能夠互換算法

簡單點理解爲定義公共方法,調用公共方法
image.pngthis

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;
            }
        });
        //因而可知,策略模式能夠隨意擴展,只要實現對應接口就行
    }
}
相關文章
相關標籤/搜索