Groovy DSLS

2022-07-21 11:31 更新

Groovy允許在頂層語句的方法調(diào)用的參數(shù)周圍省略括號。這被稱為“命令鏈”功能。這個(gè)擴(kuò)展的工作原理是允許一個(gè)人鏈接這種無括號的方法調(diào)用,在參數(shù)周圍不需要括號,也不需要鏈接調(diào)用之間的點(diǎn)。

如果一個(gè)調(diào)用被執(zhí)行為bcd,這將實(shí)際上等價(jià)于a(b).c(d)。

DSL或域特定語言旨在簡化以Groovy編寫的代碼,使得它對于普通用戶變得容易理解。以下示例顯示了具有域特定語言的確切含義。

def lst = [1,2,3,4] 
print lst

上面的代碼顯示了使用println語句打印到控制臺的數(shù)字列表。在域特定語言中,命令將是 -

Given the numbers 1,2,3,4
 
Display all the numbers

所以上面的例子顯示了編程語言的轉(zhuǎn)換,以滿足領(lǐng)域特定語言的需要。

讓我們來看一個(gè)簡單的例子,我們?nèi)绾卧贕roovy中實(shí)現(xiàn)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" 
}

當(dāng)我們運(yùn)行上面的程序,我們將得到以下結(jié)果 -

How are things? We are doing well. Take care

以下需要注意上面的代碼實(shí)現(xiàn) -

  • 使用接受閉包的靜態(tài)方法。這是一個(gè)很麻煩的方式來實(shí)現(xiàn)DSL。

  • 在電子郵件示例中,類EmailDsl具有make方法。它創(chuàng)建一個(gè)實(shí)例,并將閉包中的所有調(diào)用委派給實(shí)例。這是一種機(jī)制,其中“to”和“from”節(jié)結(jié)束了EmailDsl類中的執(zhí)行方法。

  • 一旦to()方法被調(diào)用,我們將文本存儲在實(shí)例中以便以后格式化。

  • 我們現(xiàn)在可以使用易于為最終用戶理解的簡單語言調(diào)用EmailDSL方法。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號