>概述
策略模式体现了Java两个设计上的原则:
策略模式的角色:
(以Comparator接口为例)
Java中Comparator比较器,提供了一种排序机制,
>Demo
待排序类型:
public class Person {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = 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 + "]";
}
}
抽象策略:
public interface PersonComparator {
public List comparatePerson(List lis, String dir);
}
具体策略(按Age排序,如果Age相同,按Id排序):
public class PersonAgeComparator implements PersonComparator {
public PersonAgeComparator() {
// TODO Auto-generated constructor stub
}
@Override
public List comparatePerson(List lis, String dir) {
if ("0".equals(dir)) {
Collections.sort(lis, (x, y) -> {
if (x.getAge() > y.getAge()) {
return 1;
} else if (x.getAge() < y.getAge()) {
return -1;
} else {
return x.getId() - y.getId();
}
});
} else {
Collections.sort(lis, (x, y) -> {
if (x.getAge() > y.getAge()) {
return -1;
} else if (x.getAge() < y.getAge()) {
return 1;
} else {
return x.getId() - y.getId();
}
});
}
return lis;
}
}
测试类:
public static void main(String[] args) {
List personLis = Arrays.asList(new Person(1, "zhangsan", 5), new Person(2, "lisi", 7),
new Person(3, "wangwu", 8), new Person(4, "zhaoliu", 5), new Person(5, "tianqi", 2),
new Person(6, "xiaoming", 10), new Person(7, "xiaolan", 5), new Person(8, "xiaozi", 15));
PersonComparator com = new PersonAgeComparator();
personLis = com.comparatePerson(personLis, "0");
personLis.forEach(x->{
System.out.println(x);
});
}
运行结果:
Person [id=5, name=tianqi, age=2]
Person [id=1, name=zhangsan, age=5]
Person [id=4, name=zhaoliu, age=5]
Person [id=7, name=xiaolan, age=5]
Person [id=2, name=lisi, age=7]
Person [id=3, name=wangwu, age=8]
Person [id=6, name=xiaoming, age=10]
Person [id=8, name=xiaozi, age=15]