Closures for Java铪
2008-04-01 17:30
323 查看
一群“聪明人”写了一份草案,要求给Java增加closure功能。所谓closure,就是类似php里面经常用到的变量函数
public static void main(String[] args) {
int plus2(int x) { return x+2; }
int(int) plus2b = plus2;
System.out.println(plus2b(2));
}
那么它如何简化现有的代码呢?看下面三个例子
1 传统的代码
public interface Runnable {
void run();
}
public interface API {
void doRun(Runnable runnable);
}
public class Client {
void doit(API api) {
api.doRun(new Runnable(){
public void run() {
snippetOfCode();
}
});
}
}
2 简化的代码
public interface API {
void doRun(void() func);
}
And the client like this:
public class Client {
void doit(API api) {
api.doRun(() {snippetOfCode(); }); // 将函数直接写在这里,省略了一个对象
}
}
3 进一步简化的代码
Runnable runnable(final void() func) {
return new Runnable() {
public void run() { func(); }
};
}
Allowing the client to write this:
public class Client {
void doit(API api) {
api.doRun(runnable(() {snippetOfCode(); })); //直接把runnable作为一个函数盒子
}
}
可以说这个功能的提出,是为了将类的方法的定义变得更加的灵活,然而这种用到时才定义的设计理念和j2ee传统的组件型的开发思想相违背。Closure何去何从,我们拭目以待。
public static void main(String[] args) {
int plus2(int x) { return x+2; }
int(int) plus2b = plus2;
System.out.println(plus2b(2));
}
那么它如何简化现有的代码呢?看下面三个例子
1 传统的代码
public interface Runnable {
void run();
}
public interface API {
void doRun(Runnable runnable);
}
public class Client {
void doit(API api) {
api.doRun(new Runnable(){
public void run() {
snippetOfCode();
}
});
}
}
2 简化的代码
public interface API {
void doRun(void() func);
}
And the client like this:
public class Client {
void doit(API api) {
api.doRun(() {snippetOfCode(); }); // 将函数直接写在这里,省略了一个对象
}
}
3 进一步简化的代码
Runnable runnable(final void() func) {
return new Runnable() {
public void run() { func(); }
};
}
Allowing the client to write this:
public class Client {
void doit(API api) {
api.doRun(runnable(() {snippetOfCode(); })); //直接把runnable作为一个函数盒子
}
}
可以说这个功能的提出,是为了将类的方法的定义变得更加的灵活,然而这种用到时才定义的设计理念和j2ee传统的组件型的开发思想相违背。Closure何去何从,我们拭目以待。
相关文章推荐
- 教案:Java第7章 类的方法
- F3: Sun的新Java脚本语言
- 2007年软件开发技术预测集锦-Java,软件开发,Ajax
- 2006 Java技术的赢家和输家
- 招聘中经常伴随Java出现的20项技术
- 教案:Java第6章 对象和类
- 教案:Java第5章 循环结构(二)
- java RMI 相关
- Struts 2.0 解读笔记
- Java平台版本号的演变
- Mule+Spring+jbpm
- Java技术随想
- 真正的maven私服搭建器--Artifactory
- 又有免费Java电子书下了
- 产生 java.lang.NoClassDefFoundError 的另一种意外情况:jar包部分的物理性损坏
- Spring 2.5 Perfomance Improvements 200% 直逼 Guice
- JavaEE事务扫盲笔记之一扫扫到尾
- Spring 开发指南
- Spring开发指南 0.8 发布
- Struts的心酸往事