课程表

Groovy课程

工具箱
速查手册

Groovy DSLS

当前位置:免费教程 » Java相关 » Groovy

Groovy允许在顶层语句的方法调用的参数周围省略括号。这被称为“命令链”功能。这个扩展的工作原理是允许一个人链接这种无括号的方法调用,在参数周围不需要括号,也不需要链接调用之间的点。

如果一个调用被执行为bcd,这将实际上等价于a(b).c(d)。

DSL或域特定语言旨在简化以Groovy编写的代码,使得它对于普通用户变得容易理解。以下示例显示了具有域特定语言的确切含义。

  1. def lst = [1,2,3,4]
  2. print lst

上面的代码显示了使用println语句打印到控制台的数字列表。在域特定语言中,命令将是 -

  1. Given the numbers 1,2,3,4
  2. Display all the numbers

所以上面的例子显示了编程语言的转换,以满足领域特定语言的需要。

让我们来看一个简单的例子,我们如何在Groovy中实现DSL -

  1. class EmailDsl {
  2. String toText
  3. String fromText
  4. String body
  5. /**
  6. * This method accepts a closure which is essentially the DSL. Delegate the
  7. * closure methods to
  8. * the DSL class so the calls can be processed
  9. */
  10. def static make(closure) {
  11. EmailDsl emailDsl = new EmailDsl()
  12. // any method called in closure will be delegated to the EmailDsl class
  13. closure.delegate = emailDsl
  14. closure()
  15. }
  16. /**
  17. * Store the parameter as a variable and use it later to output a memo
  18. */
  19. def to(String toText) {
  20. this.toText = toText
  21. }
  22. def from(String fromText) {
  23. this.fromText = fromText
  24. }
  25. def body(String bodyText) {
  26. this.body = bodyText
  27. }
  28. }
  29.  
  30. EmailDsl.make {
  31. to "Nirav Assar"
  32. from "Barack Obama"
  33. body "How are things? We are doing well. Take care"
  34. }

当我们运行上面的程序,我们将得到以下结果 -

  1. How are things? We are doing well. Take care

以下需要注意上面的代码实现 -

  • 使用接受闭包的静态方法。这是一个很麻烦的方式来实现DSL。

  • 在电子邮件示例中,类EmailDsl具有make方法。它创建一个实例,并将闭包中的所有调用委派给实例。这是一种机制,其中“to”和“from”节结束了EmailDsl类中的执行方法。

  • 一旦to()方法被调用,我们将文本存储在实例中以便以后格式化。

  • 我们现在可以使用易于为最终用户理解的简单语言调用EmailDSL方法。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号