The Delegation Pattern is a technique where an object's behavior (public methods) is implemented by delegating responsibility to one or more associated objects.
Groovy allows the traditional style of applying the delegation pattern, e.g. see Replace Inheritance with Delegation.
In addition, the ExpandoMetaClass allows usage of this pattern to be encapsulated in a library.
Consider the following library class:
With this in your classpath, you can now apply the delegation pattern dynamically as shown in the following examples. First, consider we have the following classes:
We can now use the delegator to automatically borrow methods from the lender object to extend the Person class. We can borrow the methods as is or with a rename:
Alternatively, we could borrow multiple methods like this:
Or if we want all the methods, like this:
Alternatively, we can use a map notation to rename multiple methods: