在策略模式(Strategy Pattern)中,一個類的行為或其算法可以在運(yùn)行時更改晕换。這種類型的設(shè)計模式屬于行為型模式。
策略模式中專門有一個對象封裝算法,以便于在運(yùn)行時調(diào)用不通算法
實(shí)現(xiàn)一個策略模式
- 對一組對象按照其相關(guān)字段進(jìn)行排序
- 排序采用簡單的插入排序
- 封裝一個transtion對象去實(shí)現(xiàn)排序規(guī)則算法(仔細(xì)看transtion封裝的代碼)
package com.snail.basic;
import java.util.Comparator;
public class Insertion {
public static void sort(Object[] a, Comparator c){
int N = a.length;
for (int i = 1; i < N; i++) {
for (int j = i; j >0 && less(c,a[j],a[j-1]); j--) {
exch(a,j,j-1);
}
}
}
public static boolean less(Comparator c,Object v,Object w){
return c.compare(v,w)<0;
}
public static void exch(Object[] a,int i,int j){
Object t = a[i];
a[i]=a[j];
a[j]=t;
}
public static void main(String[] args) {
// 隨意幾個對象 包含who when amount 等字段,按照不同字段排序
Object[] a = new Object[5];
Insertion.sort(a,new Transaction.WhoOrder());
Insertion.sort(a,new Transaction.WnenOrder());
Insertion.sort(a,new Transaction.HowMuchOrder());
}
}
package com.snail.basic;
import java.util.Comparator;
import java.util.Date;
public class Transaction {
private final String who = null;
private final Date when = null;
private final double amount = 0.0;
public static class WhoOrder implements Comparator<Transaction>{
@Override
public int compare(Transaction v, Transaction w) {
return v.who.compareTo(w.who);
}
}
public static class WnenOrder implements Comparator<Transaction>{
@Override
public int compare(Transaction v, Transaction w) {
return v.when.compareTo(w.when);
}
}
public static class HowMuchOrder implements Comparator<Transaction>{
@Override
public int compare(Transaction v, Transaction w) {
if(v.amount < w.amount) return -1;
if(v.amount > w.amount) return +1;
return 0;
}
}
}