...
| Code Block |
|---|
peg SquarePegAdapter with width 4 (and notional radius 2.8284271247461903) fits in hole RoundHole with radius 4.0 peg SquarePegAdapter with width 5 (and notional radius 3.5355339059327378) fits in hole RoundHole with radius 4.0 peg SquarePegAdapter with width 6 (and notional radius 4.242640687119285) does not fit in hole RoundHole with radius 4.0 peg SquarePegAdapter with width 7 (and notional radius 4.949747468305833) does not fit in hole RoundHole with radius 4.0 |
...
Adapting using Closures
As a variation of the previous examples, we could instead define the following interface:
| Code Block |
|---|
interface RoundThing {
def getRadius()
}
|
We can then define an adapter as a closure as follows:
| Code Block |
|---|
def adapter = {
p -> [getRadius:{Math.sqrt(((p.width/2) ** 2)*2)}] as RoundThing
}
|
And use it like this:
| Code Block |
|---|
def peg = new SquarePeg(width:w)
if (hole.pegFits(adapter(peg)))
// ... as before
|
Adapting using the ExpandoMetaClass
As of Groovy 1.1, there is a built-in MetaClass which can automatically add properties and methods dynamically.
...