Groovy-15.DSLS

2019-05-30 15:00:40 浏览数 (1)

“命令链”功能:允许在顶层语句的方法调用的参数周围省略括号。也就是在参数周围不需要括号,也不需要链接调用之间的点号。 DSL(Domain Specific Languages 领域定义语言)以简化代码,Groovy中的DSL:

代码语言:javascript复制
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" 
}

其结果为:

代码语言:javascript复制
How are things? We are doing well. Take care

0 人点赞