Skip to end of metadata
Go to start of metadata

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:

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:

Adapting using Closures

As a variation of the previous examples, we could instead define the following interface:

We can then define an adapter as a closure as follows:

And use it like this:

Adapting using 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.

  • No labels