|
Posted on 2008-03-10 21:47 蜀山兆孨龘 阅读(378) 评论(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));
- }
-
- }
|
|