參考: think in java
//定義一個介面
interface Incrementable...{
void increment();
}
//一個簡單的介面實作類別
class Callee1 implements Incrementable...{
private int i = 0;
public void increment()...{
i++;
System.out.println (i);
}
}
class MyIncrement...{
void increment()...{
System.out.println ("other operator");
}
static void f(MyIncrement mi)
...{
mi.increment();
}
}
//Callee2 想改變 MyIncrement中 increment()方法的行為。
// 主要是因為Callee2有一個完全不同的incr ()方法
// 要解決的問題是在調用increment 方法的時候 改而調用 incr方法
//父類有一個increment 不能因為字類的用途而覆蓋這個方法
//所以字類重新寫了一個 incr 方法。
class Callee2 extends MyIncrement...{
private int i = 0;
//一個用來替代incrment方法的行為的方法。
private void incr()...{
i++;
System.out.println (i);
}
//內部類實現Incrementable介面
private class Closure implements Incrementable ...{
public void increment()...{
incr();
}
}
//獲得一個回調的引用
Incrementable getCallBackReference()...{
return new Closure();
}
}
class Caller...{
private Incrementable callbackReferences;
//它只需要一個介面。
Caller (Incrementable chb)...{
callbackReferences = chb;
}
void go()...{
callbackReferences.increment();
}
}
class Callbacks...{
public static void main(String[] args)...{
Callee1 c1 = new Callee1();
Callee2 c2 = new Callee2();
MyIncrement.f(c2);
Caller caller1 = new Caller(c1);
//用戶端完全不知道 caller2 中的incrment方法的實現。
//事實上Callee2完全改變了incrment方法的行為(調用了另一個方法)
Caller caller2 = new Caller(c2.getCallBackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
}
//回調的價值在於它的靈活性--在運行時決定調用哪個方法。