「好萊塢原則」:**Don't call us, we'll call you.** 高層模組定義介面,低層模組在特定時機呼叫高層提供的實作。Java 無指標,透過介面實現回呼。
public interface CallBackInterface {
void doSome();
void executeMethod();
}
public class MethodB {
public double getTime(CallBackInterface callback) {
long start = System.currentTimeMillis();
callback.executeMethod(); // 回呼執行
long end = System.currentTimeMillis();
System.out.println("cost time=" + (end - start));
return end - start;
}
}
public class MethodA {
public static void main(String[] args) {
MethodB b = new MethodB();
double d = b.getTime(new CallBackInterface() {
@Override
public void executeMethod() {
new MethodA().testMethod(); // 實際業務邏輯
}
@Override
public void doSome() {}
});
System.out.println("d=" + d);
}
public void testMethod() {
for (int i = 0; i < 10000; i++) System.out.print("");
}
}