|
Posted on 2008-03-10 21:47 蜀山兆孨龘 閱讀(383) 評論(0) 編輯 收藏
用接口實現回調 |
Implementing Callback with Interface |
C 語言里的函數指針,JavaScript 里的函數參數可以實現回調,從而完成很多動態功能。請看下面的 JavaScript 代碼: |
C's function pointer and JavaScript's function parameter can implement callback, accomplishing lots of dynamic functionalities. Please look at the following JavaScript code: |
- function add(a, b) {
- return a + b;
- }
-
- function sub(a, b) {
- return a - b;
- }
-
- function cal(a, b, callback) {
- alert(callback(a, b));
- }
-
- cal(2, 1, add);
- cal(2, 1, sub);
- cal(2, 1, function (a, b) {
- return a * b;
- });
|
在對 cal 函數的三次調用中,變量 callback 分別指向三個函數(包括一個匿名函數),從而在運行時產生不同的邏輯。如果仔細研究網上各種開源的 JS 庫,會發現大量此類回調。 |
In the three invokings to function cal, variable callback points to three different functions (including one anonymous function), which generates different logics at runtime. If you study various open source JS libraries on the Internet in depth, you will find many callbacks of this kind. |
Java 語言本身不支持指針,所以無法像 JavaScript 那樣將方法名直接作為參數傳遞。但是利用接口,完全可以達到相同效果: |
Java language itself doesn't support pointer, so the method name can't be directly passed as a parameter like JavaScript. But with interface, the completely same effect can be achieved: |
- public interface Cal {
-
- public int cal(int a, int b);
-
- }
-
- public class Add implements Cal {
-
- public int cal(int a, int b) {
- return a + b;
- }
-
- }
-
- public class Sub implements Cal {
-
- public int cal(int a, int b) {
- return a - b;
- }
-
- }
-
- public class Test {
-
- public static void main(String[] args) {
- test(2, 1, new Add());
- test(2, 1, new Sub());
- test(2, 1, new Cal() {
- public int cal(int a, int b) {
- return a * b;
- }
- });
- }
-
- private static void test(a, b, Cal c) {
- System.out.println(c.cal(a, b));
- }
-
- }
|
|