- public class Person implements ICompare {
-
- private int age;
- private float height;
- private float weight;
-
- public Person(int age, float height, float weight) {
- super();
- this.age = age;
- this.height = height;
- this.weight = weight;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public float getHeight() {
- return height;
- }
-
- public void setHeight(float height) {
- this.height = height;
- }
-
- public float getWeight() {
- return weight;
- }
-
- public void setWeight(float weight) {
- this.weight = weight;
- }
-
- @Override
- public int comparable(ICompare obj) {
- Person p = (Person)obj;
- return this.age - p.age;
- }
-
- }
测试:
- public class CallBackTest {
-
- public static void Sort(ICompare[] objs) {
- int n = objs.length;
- for(int i = 0; i < n-1; i ++) {
- for(int j = 0; j < n-i-1; j ++) {
- if(objs[j].comparable(objs[j + 1]) > 0)
- {
- ICompare temp = objs[j];
- objs[j] = objs[j + 1];
- objs[j + 1] = temp;
- }
- }
- }
- }
-
- public static void showArray(Person persons[]){
- for(int i = 0; i < persons.length; i ++) {
- System.out.println("age:" + persons[i].getAge() + " weight:" + persons[i].getWeight() + " height:" + persons[i].getWeight());
- }
- }
-
-
-
-
- public static void main(String[] args) {
- Person[] persons = new Person[]{
- new Person(2, 54.5f, 0.82f),
- new Person(31, 74.5f, 1.80f),
- new Person(54, 44.5f, 1.59f),
- new Person(23, 62.0f, 1.78f),
- new Person(16, 45.7f, 1.60f)
- };
- System.out.println("before sort:");
- showArray(persons);
- Sort(persons);
- System.out.println("after sort:");
- showArray(persons);
- }
-
- }
java.util.Arrays中的Sort就用到了这种技术,从Java的API中可以看出:
public static void sort(Object[] a)
根据元素的自然顺序,对指定对象数组按升序进行排序。数组中的所有元素都必须实现 Comparable 接口。此外,数组中的所有元素都必须是可相互比较的(也就是说,对于数组中的任何 e1 和 e2 元素而言,e1.compareTo(e2) 不得抛出 ClassCastException)。
回调之编程思想
在软件模块调用中,主要有三种机制:同步调用,异步调用和回调。
同步调用是调用方(A)call被调用方(B)的接口,并等待B处理完给出一个回执后A才继续执行,这期间是“阻塞”的。
异步调用是调用方(A)call被调用方(B)的接口后,不等待B执行完,且B在被调用后会直接回执A。
回调是调用方(A)call被调用方(B)时,B也回调(callback)被调用方,双方互调接口,只不过call动作是由A发起的。
同步调用是最简单的,异步调用一般是在回调的基础上实现的。所以了解“回调”的机制是至关重要的。
我们再来看一个例子,用程序模拟“八仙过海,各显神通”。
结果如下:
铁拐李将葫芦变成条葫芦大船过海...
张果老将毛驴变成一只小黑驴过海...
何仙姑将荷叶往海面上一铺,躬身往上一跃,漂浮而去过海...
韩湘子将玉箫往水中一掷,化作一根浮木,站在上面过海...
吕洞宾把黄龙宝剑投入海中,宝剑化作一只小船载着他过海...
蓝采和将百花篮变成五彩船悠哉游哉坐上彩船过海...
汉钟离有一把芭蕉扇,他来了一个鲤鱼大翻 身,躺在扇子上悠闲自得地随波飘荡过海...
上面这个例子中Immortal是一个接口,doMagic就是你要实现的回调函数,传递了这个接口的对象也就传递了这个回调函数的实现,也就是实现了回调。
是不是很有趣?对,就是这么一个有有趣的例子,却淋漓尽致地表现了Java中回调的精髓,你可以反复地体会。上面这个例子在设计模式中也叫观察者模式,大家在别的地方看它的用法就不要再觉得陌生了哦!
恰当地使用回调,有以下的作用:
避免重复代码
在你需要更多的通用功能的地方更好地实现抽象(可处理各种类型的对象和变量)。
增强代码的可维护性
增强代码的可读性
有更多定制的功能