Groovy - DSL



Groovy 允許在頂級語句中省略方法呼叫引數周圍的括號。這被稱為“命令鏈”功能。此擴充套件透過允許將此類無括號方法呼叫連結起來,既不需要引數周圍的括號,也不需要連結呼叫之間的點來工作。

如果呼叫以 a b c d 的形式執行,則實際上等效於 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 方法,以便終端使用者理解。

廣告