神奇好望角 The Magical Cape of Good Hope

庸人不必自扰,智者何需千虑?
posts - 26, comments - 50, trackbacks - 0, articles - 11
  BlogJava :: 首页 ::  :: 联系 :: 聚合  :: 管理

用接口实现回调

Posted on 2008-03-10 21:47 蜀山兆孨龘 阅读(380) 评论(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:
  1. function add(a, b) {
  2.     return a + b;
  3. }
  4. function sub(a, b) {
  5.     return a - b;
  6. }
  7. function cal(a, b, callback) {
  8.     alert(callback(a, b));
  9. }
  10. cal(2, 1, add);
  11. cal(2, 1, sub);
  12. cal(2, 1, function (a, b) {
  13.     return a * b;
  14. });
  在对 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:
  1. public interface Cal {
  2.     public int cal(int a, int b);
  3. }
  4. public class Add implements Cal {
  5.     public int cal(int a, int b) {
  6.         return a + b;
  7.     }
  8. }
  9. public class Sub implements Cal {
  10.     public int cal(int a, int b) {
  11.         return a - b;
  12.     }
  13. }
  14. public class Test {
  15.     public static void main(String[] args) {
  16.         test(2, 1, new Add());
  17.         test(2, 1, new Sub());
  18.         test(2, 1, new Cal() {
  19.             public int cal(int a, int b) {
  20.                 return a * b;
  21.             }
  22.         });
  23.     }
  24.     private static void test(a, b, Cal c) {
  25.         System.out.println(c.cal(a, b));
  26.     }
  27. }

只有注册用户登录后才能发表评论。


网站导航: