Builder Pattern Made Groovy

In Java, you might have come across with a class that has a ton of constructors, each of the constructor with a different number and arrangement of parameters. This usually happens because some of the parameters are optional or when there are different flavors of accepted parameter types. One way to clean up this type of situation is to use the Builder design pattern advocated by the Gang of Four in the seminal book Design Patterns: Elements of Reusable Object-Oriented Software. The builder pattern is a creational pattern which simplifies the creation of complex objects.

Groovy elevates the promotion of the builder pattern with the core Groovy Development Kit (GDK) making builders as commonplace and habitual for the average developer as Iterators. Groovy provides the NodeBuilder, MarkupBuilder, AntBuilder and the SwingBuilder to facilitate the constructor of nested object hierarchies, XML/HTML, ant tasks, and Swing components. But perhaps more importantly, the GDK provides the abstract class BuilderSupport which can be extended to create custom builders.

The way that MarkupBuilder works, for example, is that once you create an instance of the builder you invoke any method passing along named parameters or a closure. You can invoke any method name that is valid to the language. Even though the builder does not implement a given method, the method invocation will be routed or relayed to a createNode method that will create a tag element out of it. The named parameters will become tag attributes. Any method calls declared in the closure will become nested tag elements. Here is a typical example of the MarkupBuilder.

StringWriter writer = new
def build = new groovy.xml.MarkupBuilder(writer)
build.html {
head {
title ‘Juixe TechKnow’
body(bgcolor: ‘#ffffff’) {
h1 ‘Hello, World’
print writer;

From the above example, you should note that the MarkupBuilder does not define or implement any HTML, head, title, body, or h1 method. Think of these methods as dynamic. When the HTML method is invoked, it will be delegated to a createNode which in this case will append an a tag named after the method into the string writer.

To drive this point home, lets define a builder of our own. The builder that I plan to write for this exercise will build a hierarchy of hashes, that is a hash of nested hashes. To create our HashBuilder we will extend the BuilderSupport abstract class that is part of the GDK. Our HashBuilder needs to implement one setParent and four createNode methods. What follows is the initial implementation of the HashBuilder class.

import groovy.util.BuilderSupport

class HashBuilder extends BuilderSupport {
protected void setParent(Object parent, Object child) {
parent[parent[‘name’]] = child

protected Object createNode(Object name) {
createNode name, null, null

protected Object createNode(Object name, Object value) {
createNode name, null, value

protected Object createNode(Object name, Map attrs) {
createNode name, attrs, null

protected Object createNode(Object name, Map attrs, Object value) {
// Create a hash/map
def node = [name:name]
node[name] = attrs // Add map to hash
return node

Once you have defined the above HashBuilder you can create a corporate hierarchy out of hash with code similar to the following trivial example.

HashBuilder apple = new HashBuilder();
print apple.departments {
management {
employee(firstname:’Steve’, lastname:’Jobs’, title:”CEO”)

As you can gather from the examples presented here, Groovy builders leverage power of meta-programming, named parameters, closures, and optional parenthesis in an concise and elegant fashion.

Technorati Tags: , , , , , , ,

One Response to “Builder Pattern Made Groovy”

Leave a Reply