W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
Groovy允許在頂層語句的方法調用的參數(shù)周圍省略括號。這被稱為“命令鏈”功能。這個擴展的工作原理是允許一個人鏈接這種無括號的方法調用,在參數(shù)周圍不需要括號,也不需要鏈接調用之間的點。
如果一個調用被執(zhí)行為bcd,這將實際上等價于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
所以上面的例子顯示了編程語言的轉換,以滿足領域特定語言的需要。
讓我們來看一個簡單的例子,我們如何在Groovy中實現(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" }
當我們運行上面的程序,我們將得到以下結果 -
How are things? We are doing well. Take care
以下需要注意上面的代碼實現(xiàn) -
使用接受閉包的靜態(tài)方法。這是一個很麻煩的方式來實現(xiàn)DSL。
在電子郵件示例中,類EmailDsl具有make方法。它創(chuàng)建一個實例,并將閉包中的所有調用委派給實例。這是一種機制,其中“to”和“from”節(jié)結束了EmailDsl類中的執(zhí)行方法。
一旦to()方法被調用,我們將文本存儲在實例中以便以后格式化。
我們現(xiàn)在可以使用易于為最終用戶理解的簡單語言調用EmailDSL方法。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: