Groovy在线运行

版本:

所属目录
点击了解高性能代码运行API
运行结果
教程手册
代码仓库
极速运行
终端运行
图形+终端

                        
用户最新保存的代码
查看更多
显示目录

DSLS



搭载国产梦丘操作系统,支持安装软件,在线编程可视化开发软件,无需配置开发环境

点击购买 梦丘固件

DSLS

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方法。

由JSRUN为你提供的Groovy在线运行、在线编译工具
        JSRUN提供的Groovy 在线运行,Groovy 在线运行工具,基于linux操作系统环境提供线上编译和线上运行,具有运行快速,运行结果与常用开发、生产环境保持一致的特点。