1. 程式人生 > >設計模式學習筆記2: 策略模式(Strategy)

設計模式學習筆記2: 策略模式(Strategy)

模擬 Comparable

public interface Comparable {
    int compareTo(Object ob);
}
public class Test {
    public static void main(String[] args) {
        Cat[] a = {new Cat(4, 3), new Cat(2, 2), new Cat(9, 4),new Cat(1, 100)};
        DataSorter.sort(a);
        DataSorter.p(a);
        System.out.println(a);
    }
}
public class Cat implements Comparable{
    private int height;
    private int weight;
    // get ,set方法略

    public int compareTo(Object ob) {
        if (ob instanceof Cat) { //左邊物件是否為其右邊類的例項
            Cat cat = (Cat) ob;
            if (this.getHeight() > cat.getHeight()) {
                return 1;
            }
            if (this.getHeight() < cat.getHeight()) {
                return -1;
            }
            return 0;
        }
        return -23333;//省去拋異常
    }

}
public class DataSorter {
    public static void sort(Object[] a) {
        for (int i = a.length; i > 0; i--) {
            for (int j = 0; j < i-1; j++) {
                Comparable ob1 = (Comparable) a[j];
                Comparable ob2 = (Comparable) a[j + 1];
                if (ob1.compareTo(ob2) == 1) {
                    swap(a, j, j + 1);
                }
            }
        }
    }

    private static void swap(Object[] a, int x, int y) {
        Object temp = a[x];
        a[x] = a[y];
        a[y] = temp;
    }
}