设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1985字,纯文字阅读大概需要3分钟。
内容图文
模板方法模式(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
原文:http://www.cnblogs.com/yfceshi/p/7381036.html
内容总结
以上是互联网集市为您收集整理的设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释全部内容,希望文章能够帮你解决设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。