策略模式和自定义排序规则
一、定义Person类模型
package cn.lesson8.statary;
public class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
二、定义接口SortInterface
package cn.lesson8.statary;
import java.util.List;
public interface SortInterface {
public void sort(List<Person> list);
}
三、实现接口的具体方法UpNameSort
该方法继承了Comparator接口,实现自定义排序规则。
package cn.lesson8.statary; import java.util.Collections; import java.util.Comparator; import java.util.List; public class UpNameSort implements SortInterface,Comparator<Person>{ @Override public int compare(Person o1, Person o2) { int result=o1.getName().compareTo(o2.getName()); if(0==result){ return o1.getId()-o2.getId(); //如果名字相等,按Id排序 } return result; } @Override public void sort(List<Person> list) { Collections.sort(list, this); //安装自定义排序规则进行排序,this代表当前的排序规则 } }
四、调用环境类Environment
package cn.lesson8.statary;
import java.util.List;
public class Environment {
private SortInterface sortInterface;
public Environment(SortInterface sortInterface){
this.sortInterface=sortInterface;
}
public Environment(){
}
public void setSortInterface(SortInterface sortInterface) {
this.sortInterface = sortInterface;
}
public void sort(List<Person> list){
this.sortInterface.sort(list); //this代表当前对象调用sortInterface对象的sort()方法
}
}
五、测试类Client
package cn.lesson8.statary;
import java.util.ArrayList;
import java.util.List;
public class Client {
public static void main(String[] args){
Person p1 = new Person();
p1.setName("Tom");
p1.setId(1);
p1.setAge(20);
Person p2 = new Person();
p2.setName("Tonny");
p2.setId(2);
p2.setAge(50);
Person p3 = new Person();
p3.setName("Tom");
p3.setId(5);
p3.setAge(30);
Person p4 = new Person();
p4.setName("ABC");
p4.setId(8);
p4.setAge(10);
Person p5 = new Person();
p5.setName("Xyz");
p5.setId(9);
p5.setAge(15);
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
Environment env=new Environment();
UpNameSort uns=new UpNameSort();
env.setSortInterface(uns);
env.sort(list);
for(int i=0;i<list.size();i++){
Person p=list.get(i);
System.out.println(p.toString());
}
}
}