text: Q:
  
  How to handle 'this' reference in decorator pattern
  
  I have a problem in a class of mine that uses the decorator pattern.
  The problem arises when the inner object uses the "this" reference in calls to other objects. This causes all calls from the object that received the "this" reference to be made directly to the inner object, without going through the outer first. 
  What is the usual way to solve this problem? 
  Thanks.
  
  A:
  
  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. 
  
  