Decorator implementing Comparable

Here’s an example to show how to implement compareTo in a decorator.

The decorator pattern is often very handy and it’s always a good idea to make things comparable if this makes any sense. (This is basically what Josh Bloch tells you in items 12 and 16 in his great book “Effecitve Java”.)

My example demonstrates how to combine both in one class.

The code is on pastebin:

It contains a main-method so just run it. Decorated values are inside brackets like this: [42]
There’s even a Proxy, which decorates as: {42}

It also contains equals. But note that for both equals and compareTo you need to define what happens if two types have more fields than IFoo defines. This usually only works if you have just one abstraction in use. You can’t have an implementation of IFoo that also implements other interfaces with their own definition of equality or natural order (i.e. you can implement both IFoo and java.util.Set).


If you have many fields you’ll have to write a lot of code. Since JavaFX is a fully integrated feature of the JRE you can instead use FXCollections.observable* to get an object decorated as an observable object. But that only works for collections (List, Map etc).
You can use Project Lombok to generate methods to forward all calls with the @Delegate-feature.
Or use a Proxy as demonstrated in the code. The InvocationHandler could call any other code. And if you use any AOP framework you can use aspects to inject code to existing beans.

Leave a Reply

Your email address will not be published. Required fields are marked *