C9) Strategy(策略模式) 定义:定义一个算法集,封装每个算法,并使得其可互换。策略模式让算法脱离调用它的客户端而独立地改变。 这个模式实际上我们经常会不自觉地用到,大部分的程序其实都是算法或者逻辑的实现,现在WorkFrame从某种角度来看,也可以称为策略模式的实际运用:将数据传递等工作交给WorkFrame来完成,程序员更多的关注于业务逻辑也就是某种数据处理算法的实现。Java中常见的Comparator接口就是一个策略模式的体现,通常在对集合类进行排序时候,我们都可以自己实现一个Comparator的算法来排列数据的先后顺序,这里说的并不是排序的算法(冒泡、分组等)而是指的Object大小的比较算法。下面是个简单的用例子,加以说明:集合中的对象为学生信息,有学号、名字两项 public class Student { private int id; private String name; } 下面是比较的算法,第一个是按照学号排序,第二个是按照名字的第一个字排序后再按照学号排序,稍微复杂点。 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实例) 2、 http://www./Patterns/PatternStrategy.aspx(英文、C#实例、UML) 3、 http://www.caterpillar./PmWiki/pmwiki.php/DesignPattern/StrategyPattern(中文、java实例、UML)推荐 4、 http://www./tech/DesignPattern/Strategy.html(日文、java实例、UML)推荐
|