模板方法模式(template method pattern) 排序(sort) 详解
本文地址: http://blog.csdn.net/caroline_wendy
参考模板方法模式(template method pattern): http://blog.csdn.net/caroline_wendy/article/details/32159455
模板方法模式的一个主要的应用是排序(sort)算法.
对象的排列方式并不是完全相同, 所以需要排序(sort)算法compareTo()可以按需要定制, 但排序方法的结构不变.
需要实现(implement)接口Comparable, 并实现接口的方法public int compareTo(Object object), 才可以使用Arrays.sort()进行排序.
具体方法:
1. 待排序的对象, 实现Comparable接口的compareTo()方法.
/** * @time 2014年6月20日 */ package template_method.sort; /** * @author C.L.Wang * */ public class Duck implements Comparable { String name; int weight; /** * */ public Duck(String name, int weight) { // TODO Auto-generated constructor stub this.name = name; this.weight = weight; } public String toString() { return name + " weighs " + weight; } public int compareTo(Object object) { Duck otherDuck = (Duck)object; if (this.weight < otherDuck.weight) { return -1; } else if (this.weight == otherDuck.weight) { return 0; } else { return 1; } } }
2. 创建待排序对象的数组, 将数组放入Arrays.sort()函数, 进行排序, 输出即可.
/** * @time 2014年6月20日 */ package template_method.sort; import java.util.Arrays; /** * @author C.L.Wang * */ public class DuckSortTestDrive { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Duck[] ducks = { new Duck("Daffy", 8), new Duck("Dewey", 2), new Duck("Howard", 7), new Duck("Louie", 2), new Duck("Donald", 10), new Duck("Huey", 2) }; System.out.println("Before sorting: "); display(ducks); Arrays.sort(ducks); System.out.println("\nAffter sorting: "); display(ducks); } public static void display(Duck[] ducks) { for (int i=0; i<ducks.length; i++) { System.out.println(ducks[i]); } } }
3. 输出:
Before sorting: Daffy weighs 8 Dewey weighs 2 Howard weighs 7 Louie weighs 2 Donald weighs 10 Huey weighs 2 Affter sorting: Dewey weighs 2 Louie weighs 2 Huey weighs 2 Howard weighs 7 Daffy weighs 8 Donald weighs 10
设计模式 - 模板方法模式(template method pattern) 排序(sort) 详解
时间: 2024-10-05 03:41:42