Delegate DSL-like

This one is a little different. We’re using the same code (the printer closure) with two different classes… in this case delegates.

Usage examples include the one below, but also things like implemented interfaces or say append in one case adds to a StringBuilder or StringBuffer and in another case it’s a stub debug that logs appends to println. There are a lot of uses for delegates.

def printer = {
append("bob was heren");
append("bob was ").append(it);

def builder = new StringBuilder();
def buffer = new StringBuffer();

printer.delegate = builder;

println printer(“outside”);

printer.delegate = buffer;

println printer(“inside”);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: