设计模式

模板方法模式(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("
Affter 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







原文地址:https://www.cnblogs.com/yfceshi/p/7381036.html