当前位置:K88软件开发文章中心编程语言JavaGroovy → 文章内容

Groovy DSLS

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 15:50:00

由 lichiabor 创建,小路依依 最后一次修改 2016-12-12 Groovy允许在顶层语句的方法调用的参数周围省略括号。这被称为“命令链”功能。这个扩展的工作原理是允许一个人链接这种无括号的方法调用,在参数周围不需要括号,也不需要链接调用之间的点。如果一个调用被执行为bcd,这将实际上等价于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() // any method called in closure will be delegated to the EmailDsl class closure.delegate = emailDsl closure() } /** * Store the parameter as a variable and use it later to output a memo */ 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方法。

Groovy DSLS