Virtual self-reference

Instructor's Guide

intro polymorphism idioms patterns events summary, Q/A, literature
A special feature of the hush widget class library is its support for the definition of new composite widgets, which provide to the application programmer the interface of a built-in (or possibly other composite) widget. To realize this flexibility, we introduced a self() function that adds another level of indirection to self-reference. For example, look at the item class below:
  class item { 
public item(String x) { _name = x; _self = null; } String name() { return exists()?self().name():_name; } public void redirect(item x) { _self = x; } boolean exists() { return _self != null; } public item self() { return exists()?_self.self():this; } item _self; String _name; };

slide: Item with self()

The item class has an instance variable _self, that can be set to an arbitrary instance of item by invoking redirect. Now, when we ask for the name of the item, it is checked whether a redirection exists. If so, the call is redirected to the instance referenced by self(), otherwise the name of the item itself is returned.
  public class go {
  public static void main(String[] args) {
  	item a = new item("a");
  	item b = new item("b");
indeed, b
} };

slide: item: go

In combination with the handle/body idiom, we can create composites offering the interface of item, providing access to one or more (inner) items. This will be further illustrated in chapter 4.

Those well-versed in design patterns will recognize the Decorator patterns (as applied in the Interviews MonoGlyph class,  [Interviews]).