策略模式--List排序
需求:根据姓名进行排序,升序或者降序,如果名字一样,就按照id升序排序,用策略模式
步骤一: 定义一个Person对象
public class Person { private Integer id; private String name; public Person(Integer id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } setters & getters... }
步骤二: 定义一个排序的接口
public interface SortInterface { public void sort(List<Person> list); }
步骤三: 定义两个策略,升序(UpNameSort)和降序(DownNameSort)
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(result == 0) { return o1.getId() - o2.getId(); } return result; } @Override public void sort(List<Person> list) { Collections.sort(list, this); } }
import java.util.Collections; import java.util.Comparator; import java.util.List; public class DownNameSort implements SortInterface, Comparator<Person>{ @Override public void sort(List<Person> list) { Collections.sort(list, this); } @Override public int compare(Person o1, Person o2) { int result = o2.getName().compareTo(o1.getName()); if(result == 0) { return o1.getId() - o2.getId(); } return result; } }
步骤四: 定义SortEnviroment
import java.util.List; public class SortEnviroment { private SortInterface sortInterface; public SortEnviroment(SortInterface sortInterface) { this.sortInterface = sortInterface; } public SortEnviroment() { } public void setSortInterface(SortInterface sortInterface) { this.sortInterface = sortInterface; } public void sort(List<Person> list) { sortInterface.sort(list); } }
步骤五:测试
import java.util.ArrayList; import java.util.List; public class SortTestMain { public static void main(String[] args) { Person p1 = new Person(1, "Java"); Person p2 = new Person(2, "Java"); Person p3 = new Person(4, "Hadoop"); Person p4 = new Person(0, "Spark"); Person p5 = new Person(6, "Storm"); Person p6 = new Person(8, "Jvm"); List<Person> sortList = new ArrayList<Person>(); sortList.add(p1); sortList.add(p2); sortList.add(p3); sortList.add(p4); sortList.add(p5); sortList.add(p6); SortInterface up = new UpNameSort(); SortEnviroment se = new SortEnviroment(up); se.sort(sortList); for(Person p : sortList) { System.out.println("name:" + p.getName() + "," + "id:" + p.getId()); } System.out.println("--------------------------"); SortInterface down = new DownNameSort(); se.setSortInterface(down); down.sort(sortList); for(Person p : sortList) { System.out.println("name:" + p.getName() + "," + "id:" + p.getId()); } } }