How to handle 'this' reference in decorator pattern

Objects have an implicit value: their identity (can be tested by applying ==). When you wrap them, you effectively hide that identity (worse, you also expose a potentially misleading identity, the identity of the wrapper itself). So an obvious approach is compensating for this by exposing the identity of the object via another way - explicitly. E.g. you might introduce a method Object getIdentity(), that returns an object really representing the intended identity, and allowing applying == to it.

The huge downside though is that you still allow == on the decorator itself, e.g. a hazard that:

  • is natural enough to be tricked into it (identity == decorator instead of identity == decorator.getIdentity())
  • silently does the wrong thing (compare with a runtime exception - good luck debugging that)

The problem would be non-existent if, for example, objects had a method like:

protected Object getIdentity() {
    return this;
}

On which == operator would be defined, so a wrapper could also wrap the identity of the wrapped object, instead of replacing it with its own.