In the template mode, the parent class defines some algorithm flows and leaves some steps (methods) empty for subclass filling.
In the array class of Java, the static method sort () is a template, which exposes a compareto method and leaves it to the subclass to specify what is greater than, equal to, and less
package com.example.template;public class Duck implements Comparable<Duck>{ private String name; private int weight; public Duck(String name, int weight){ this.name = name; this.weight = weight; } public String toString(){ return "name" + name + "weight" + weight; } @Override public int compareTo(Duck other) { if(this.weight < other.weight){ return -1; }else if(this.weight > other.weight){ return 1; } return 0; }}
package com.example.template;import java.util.Random;public class Employee implements Comparable<Employee> { private String name; private int id; private double salary; public Employee(String name, double salary){ this.name = name; this.salary = salary; Random ra = new Random(); this.id = ra.nextInt(1000000); } public String toString(){ return "name:" + name + " salary:" + salary + " ElyId:" + id; } @Override public int compareTo(Employee other) { if(this.id < other.id){ return -1; }else if(this.id > other.id){ return 1; } return 0; }}
package com.example.template;import java.util.Arrays;public class Test { public static void main(String[] args) { Duck[] ducks = new Duck[4]; ducks[0] = new Duck("Jason", 89); ducks[1] = new Duck("Amemle", 100); ducks[2] = new Duck("Mike", 72); ducks[3] = new Duck("Ham", 102); System.out.println("before sort:"); for(int i = 0 ; i < ducks.length ; i++) System.out.println(ducks[i].toString()); Arrays.sort(ducks); System.out.println("after sort:"); for(int i = 0 ; i < ducks.length ; i++) System.out.println(ducks[i].toString()); Employee[] emps = { new Employee("Jason", 999.0), new Employee("Canson", 1599.1), new Employee("Jack", 887.9) }; System.out.println("--------------------"); System.out.println("before sort:"); for(int i = 0 ; i < emps.length ; i++) System.out.println(emps[i].toString()); Arrays.sort(emps); System.out.println("after sort:"); for(int i = 0 ; i < emps.length ; i++) System.out.println(emps[i].toString()); }}
Result:
Before sort:
Namejasonweight89
Nameamemleweight100
Namemikeweight72
Namehamweight102
After sort:
Namemikeweight72
Namejasonweight89
Nameamemleweight100
Namehamweight102
--------------------
Before sort:
Name: Jason salary: 999.0 elyid: 502862
Name: canson salary: 1599.1 elyid: 716871
Name: Jack salary: 887.9 elyid: 552929
After sort:
Name: Jason salary: 999.0 elyid: 502862
Name: Jack salary: 887.9 elyid: 552929
Name: canson salary: 1599.1 elyid: 716871
Template mode and comparable class