模板模式中,父类规定好了一些算法的流程,并且空出一些步骤(方法)留给子类填充
Java的数组类中静态方法sort()就是一个模板,它空出了一个compareTo的方法,留给子类填充,用来规定什么是大于、等于和小于
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()); } }
结果:
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
时间: 2024-10-27 13:17:07