Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 10

[ 269 ]

We then define a factory class for the customer object. The methods that we need to
implement are isLeaf (returns false), newInstance (to create the customer object),
and onNodeCompleted (to save it):


public class CustomerFactory extends AbstractFactory {

public boolean isLeaf() {
return false
}

public Object newInstance(FactoryBuilderSupport builder,
Object name, Object value, Map attributes
) throws InstantiationException, IllegalAccessException {
Customer customer = null
if (attributes != null)
customer = new Customer(attributes)
else
customer = new Customer()
return customer
}

public void onNodeCompleted(FactoryBuilderSupport builder,
Object parent, Object customer) {
customer.save()
}
}

The factory for invoices is equally straightforward. The only addition is that we
need to take care of the parent-child relationship between customer and invoice.
We do this by adding a setParent method, which will call addToInvoices on the
customer object if required. We also need to check the value parameter passed to
newInstance to see whether a parent is being set at this point:


public class InvoiceFactory extends AbstractFactory {

public boolean isLeaf() {
return false
}

public Object newInstance(FactoryBuilderSupport builder,
Object name, Object value, Map attributes
) throws InstantiationException, IllegalAccessException {
Invoice invoice = null
if (attributes != null)
invoice = new Invoice(attributes)
Free download pdf