Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

The Adapter Pattern (sometimes called the wrapper pattern) allows objects satisfying one interface to be used where another type of interface is expected. There are two typical flavours of the pattern: the delegation flavour and the inheritance flavour.

Delegation Example

Suppose we have the following classes (inspired by this):

We can ask the RoundHole class if a RoundPeg fits in it, but if we ask the same question for a SquarePeg, then it will fail because the SquarePeg class doesn't have a radius property (i.e. doesn't satisfy the required interface).

To get around this problem, we can create an adapter to make it appear to have the correct interface. It would look like this:

We can use the adapter like this:

Which results in the following output:

Inheritance Example

Let's consider the same example again using inheritance. First, here are the original classes (unchanged):

An adapter using inheritance:

Using the adapter:

The output:

Adding Dynamic Capability with the ExpandoMetaClass

As of Groovy 1.1, there is a built-in MetaClass which can automatically add properties and methods dynamically.

Here is how the example would work using that feature:

After you create a peg object, you can simply add a property to it on the fly. No need to change the original class and no need for an adapter class.

Note that at the moment you have to be using Groovy 1.1 (currently in beta) and you have to initialise the new MetaClass with the following code:

The need for this last line may go away before the final release of Groovy 1.1.

  • No labels