使用 Google Web Toolkit 和 Eclipse Galileo 进行高性能 Web 开发
2009-12-13 00:00:00 来源:WEB开发网
Listing 11. Thing 的多个实现public class Company implements Thing {
private final String name;
public Company(String name){
this.name = name;
}
public String getName() {
return this.name;
}
}
// client code
final TextBox nameField = new TextBox();
Thing user = new Person("GWT", "User");
Thing userCompany = new Company("ACME");
nameField.setText(userCompany.getName() + " " + user.getName());
清单 12 显示由 GWT 编译器发出的 JavaScript。
清单 12. 编译后的多个实现user = $Person(new Person(), 'GWT', 'User');
userCompany = $Company(new Company(), 'ACME');
$setText_2(nameField, userCompany.name_0 + ' ' + (user.firstName + ' ' + user.lastName));
可以看出,编译器仍然删除接口并内联 getName() 方法的每个实现,这仍然是非常优化的代码。但是,您可以做两件事来阻止优化,如清单 13 所示。
清单 13. 阻止编译器优化private String mkString(Collection<Thing> things, char separator){
StringBuilder sb = new StringBuilder();
for (Thing thing : things){
sb.append(thing.getName());
sb.append(separator);
}
return sb.deleteCharAt(sb.length()).toString();
}
// client code
final TextBox nameField = new TextBox();
Thing user = new Person("GWT", "User");
Thing userCompany = new Company("ACME");
nameField.setText(mkString(Arrays.asList(user, userCompany), ' '));
更多精彩
赞助商链接