目录

Groovy - DSLS

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

如果执行调用为abcd ,则实际上相当于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方法。

↑回到顶部↑
WIKI教程 @2018