Groovy DSLS


当前第2页 返回上一页

让我们来看一个简单的例子,我们如何在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

返回前面的内容

相关阅读 >>

Groovy 方法

Groovy 数据库

Groovy 可选

Groovy json

Groovy 文件io

Groovy 构建器

Groovy 注释

Groovy 变量

Groovy 数字

Groovy booleans

更多相关阅读请进入《Groovy》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...