Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Groovy allows the traditional style of applying the delegation pattern, e.g. see Replace Inheritance with Delegation.In addition, the ExpandoMetaClass

Implement Delegation Pattern using ExpandoMetaClass

The ExpandoMetaClass allows usage of this pattern to be encapsulated in a library. This allows Groovy to emulate similar libraries available for the Ruby language.

...

Code Block
delegator.delegateAll borrowAmount:'getMoney', borrowFor:'getThing'

Implement Delegation Pattern using @Delegate annotation

Since version 1.6 you can use the built-in delegation mechanism which is based on AST transformation.
This make delegation even easier:

Code Block

class Person {
    def name
    @Delegate MortgageLender mortgageLender = new MortgageLender()
}

class MortgageLender {
    def borrowAmount(amount) {
       "borrow \$$amount"
    }
    def borrowFor(thing) {
       "buy $thing"
    }
}

def p = new Person()

assert "buy present" == p.borrowFor('present')
assert "borrow $50" == p.borrowAmount(50)