Groovy - DSLS
Groovy 允许省略顶级语句的方法调用的参数周围的括号。 这称为 "command chain" 功能。 此扩展通过允许链接此类无括号的方法调用来工作,既不需要括号围绕参数,也不需要链接调用之间的点。
如果调用以 a b c d 的形式执行,这实际上等同于 a(b).c(d)。
DSL 或领域特定语言旨在简化用 Groovy 编写的代码,使普通用户易于理解。 以下示例显示了具有特定领域语言的确切含义。
def lst = [1,2,3,4] print lst
上面的代码显示了使用 println 语句打印到控制台的数字列表。 在特定领域的语言中,命令将是 −
Given the numbers 1,2,3,4 Display all the numbers
所以上面的例子展示了编程语言的转换,以满足特定领域语言的需求。
让我们看一个如何在 Groovy 中实现 DSL 的简单示例 −
class EmailDsl {
String toText
String fromText
String body
/**
* This method accepts a closure which is essentially the DSL. Delegate the
* closure methods to
* the DSL class so the calls can be processed
*/
def static make(closure) {
EmailDsl emailDsl = new EmailDsl()
// 闭包中调用的任何方法都将委托给 EmailDsl 类
closure.delegate = emailDsl
closure()
}
/**
* 将参数存储为变量,稍后使用它来输出备忘录
*/
def to(String toText) {
this.toText = toText
}
def from(String fromText) {
this.fromText = fromText
}
def body(String bodyText) {
this.body = bodyText
}
}
EmailDsl.make {
to "Nirav Assar"
from "Barack Obama"
body "How are things? We are doing well. Take care"
}
当我们运行上面的程序时,会得到下面的结果 −
How are things? We are doing well. Take care
上述代码实现需要注意以下几点 −
使用接受闭包的静态方法。 这主要是实现 DSL 的一种轻松的方式。
在电子邮件示例中,EmailDsl 类有一个 make 方法。 它创建一个实例并将闭包中的所有调用委托给该实例。 这是"to"和"from"部分最终在 EmailDsl 类中执行方法的机制。
调用 to() 方法后,我们将文本存储在实例中以供稍后格式化。
我们现在可以用一种最终用户易于理解的简单语言来调用 EmailDSL 方法。

