C9) Strategy(策略模式) 定義:定義一個(gè)算法集,封裝每個(gè)算法,并使得其可互換。策略模式讓算法脫離調(diào)用它的客戶端而獨(dú)立地改變。 這個(gè)模式實(shí)際上我們經(jīng)常會(huì)不自覺地用到,大部分的程序其實(shí)都是算法或者邏輯的實(shí)現(xiàn),現(xiàn)在WorkFrame從某種角度來看,也可以稱為策略模式的實(shí)際運(yùn)用:將數(shù)據(jù)傳遞等工作交給WorkFrame來完成,程序員更多的關(guān)注于業(yè)務(wù)邏輯也就是某種數(shù)據(jù)處理算法的實(shí)現(xiàn)。Java中常見的Comparator接口就是一個(gè)策略模式的體現(xiàn),通常在對(duì)集合類進(jìn)行排序時(shí)候,我們都可以自己實(shí)現(xiàn)一個(gè)Comparator的算法來排列數(shù)據(jù)的先后順序,這里說的并不是排序的算法(冒泡、分組等)而是指的Object大小的比較算法。下面是個(gè)簡(jiǎn)單的用例子,加以說明:集合中的對(duì)象為學(xué)生信息,有學(xué)號(hào)、名字兩項(xiàng) public class Student { private int id; private String name; } 下面是比較的算法,第一個(gè)是按照學(xué)號(hào)排序,第二個(gè)是按照名字的第一個(gè)字排序后再按照學(xué)號(hào)排序,稍微復(fù)雜點(diǎn)。 public class StudIdComp implements Comparator { public int compare(Object o1, Object o2) { if (o1 instanceof Student && o2 instanceof Student) { return ((Student)o1).getId() - ((Student)o2).getId(); }else throw new ClassCastException("not Student"); } public boolean equals(Object obj) { return this.equals(obj); } } public class StudNmIdComp implements Comparator { public int compare(Object o1, Object o2) { if (o1 instanceof Student && o2 instanceof Student) { String n1 = ((Student)o1).getName().substring(0,1); String n2 = ((Student)o2).getName().substring(0,1); int c = n1.compareTo(n2); if (c == 0) { return ((Student)o1).getId() - ((Student)o2).getId(); }else return c; }else throw new ClassCastException("not Student"); } public boolean equals(Object obj) { return this.equals(obj); } } 客戶端使用Collections.sort(studentList,new StudNmIdComp());就可以完成第二種的排序,也可以按照要求作出不同的比較算法。
參考: 1、 http://www./designpatterns/designpattern_Strategy.htm(中文、java實(shí)例) 2、 http://www./Patterns/PatternStrategy.aspx(英文、C#實(shí)例、UML) 3、 http://www.caterpillar./PmWiki/pmwiki.php/DesignPattern/StrategyPattern(中文、java實(shí)例、UML)推薦 4、 http://www./tech/DesignPattern/Strategy.html(日文、java實(shí)例、UML)推薦
|