Template Method Mode (template methods pattern) sort (sort) detailed
This article address: Http://blog.csdn.net/caroline_wendy
Reference Template Method mode (template methods pattern): http://blog.csdn.net/caroline_wendy/article/details/32159455
One of the main applications of template method Patterns is the sort algorithm .
Objects are not arranged in exactly the same way, so the sort algorithm needs to be compareTo () can be customized as needed, but the structure of the sorting method is unchanged.
You need to implement the (implement) interface comparable, and implement the interface's method public int CompareTo (object)before you can sort by using arrays.sort ().
Specific methods:
1. Objects to be sorted to implement the CompareTo () method of the comparable interface .
/**
* @time June 20, 2014 * * *
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. Create the object to be sorted
Array, put the array into
Arrays.sort ()function, sort it out, and output it.
/**
* @time June 20, 2014 * * *
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 ("Daff Y ", 8),
new Duck (" Dewey ", 2),
new Duck (" Howard ", 7),
new Duck (" Louie ", 2),
new Duck (" Donald ", 10), C20/>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.
Output:
Before sorting:
Daffy weighs 8
Dewey weighs 2
Howard weighs 7
Louie weighs 2
Donald weighs
Hue Y weighs 2
affter sorting:
Dewey weighs 2
Louie weighs 2
Huey weighs 2
Howard weighs 7
Daffy Wei GHS 8
Donald weighs 10