© Adam L. Davis 2019
Adam L. DavisLearning Groovy 3https://doi.org/10.1007/978-1-4842-5058-7_6

6. Groovy Design Patterns

Adam L. Davis1 
(1)
New York, NY, USA
 

Design patterns are a great way to make your code functional, readable, and extensible. There are some patterns that are easier and require less code in Groovy compared to Java.

Strategy Pattern

Imagine you have three different methods for finding totals as follows:
 1   def totalPricesLessThan10(prices) {
 2           int total = 0
 3           for (int price : prices)
 4                   if (price < 10) total += price
 5           total
 6   }
 7    def totalPricesMoreThan10(prices) {
 8               int total = 0
 9               for (int price : prices)
10                       if (price > 10) total ...

Get Learning Groovy 3: Java-Based Dynamic Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.