2010-07-27

what are delegates? not oop!

7.25: web.adda/delegates:

replacing delegates with inner classes:
. Sun believes bound method references [delegates]
are unnecessary because
another design alternative, inner classes,
provides equal or superior functionality.
In particular,
inner classes fully support the requirements
of user-interface event handling,
Programs that use delegation patterns
are easily expressed with inner classes.
In the AWT event model,
user-interface components send
event notifications by invoking methods of
one or more delegate objects
that have registered themselves with the component.
A button is a very simple GUI component
that signals a single event when pressed.
Here is an example using the JButton class:
[. this is my conversion of Java to adda:]
SimpleExample.class extends JPanel:
  button.JButton = ("Hello, world")
  ;
  ButtonClick.class implements ActionListener:
  ( actionPerformed(e.ActionEvent).proc:
       println("Hello, world!")
  )  ...
  init(x):
    ( x`button`addActionListener(anon.x`ButtonClick)
    ; add(x`button)
    )
** vs delegates: **
SimpleExample.class extends JPanel:
  button.JButton = ("Hello, world")
  ;
  button_clicked(e.ActionEvent).void:
    println("Hello, world!")
  ...
  init(x):
    (x`button`addActionListener(
       anon.ActionDelegate(x`button_clicked`body))
    ; add(button)
    )
. in this case, the delegate is an enclosing object.
Keeping the identifiers the same
to make the remaining differences stand out clearly:
When the user clicks on the button,
it invokes the actionPerformed method
of its delegate,
which can be of any class that implements
the ActionListener interface.
In a language that uses
bound method references,[delegates]
the corresponding code
would be quite similar. Again,
a button delegates a click to an action method.
The key conclusion is quite simple:
Any use of [a delegate] to a private method
can be transformed,
in a simple and purely local way,
into an equivalent program
using a one-member private class.
Unlike the original,
the transformed program will compile under
any JDK 1.1-compliant Java compiler.

[. delegates] require the programmer to
flatten the code of the application
into a single class
and choose a new identifier for each action method,
whereas
the use of adapter objects
requires the programmer to nest the action method
in a subsidiary class
and choose a new identifier for the class name.

No comments:

Post a Comment