ポリシー・モードとカスタム・ソート・ルール
3292 ワード
一、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);
}
三、インタフェースを実現する具体的な方法UpName Sort
この方法は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());
}
}
}