Computer science and Perl programming : best of the Perl Journal by Orwant Jon

Computer science and Perl programming : best of the Perl Journal by Orwant Jon

Author:Orwant, Jon
Language: eng
Format: epub
Tags: Perl (Computer program language), Computer science
Publisher: Beijing ; Cambridge, [Mass.] : O'Reilly
Published: 2003-06-14T16:00:00+00:00


Example 37-1. Window subclasses with polymorphic receive_event methods (continued)

else { $self->SUPER::receive_event($event,$mode) }

}

package MovableWindow; @ISA = qw( Window );

sub receive_event {

my ($self, $event, $mode) = @_;

if ($event->isa(MoveEvent) && $mode->isa(OnMode))

{ print "Moving window $self->{_id}!\n" } else { $self->SL)PER::receive_event($event,$mode) } }

package ResizableWindow; @ISA = qw( MovableWindow );

sub receive_event {

my ($self, $event, $mode) = @_;

if ($event->isa(MoveAndResizeEvent) && $mode->isa(OnMode))

{ print "Moving and resizing window $self->{_id}!\n" } elsif ($event->isa(ResizeEvent) && $mode->isa(OnMode))

{ print "Resizing window $self->{_id}!\n" } else { $self->SUPER::receive_event($event,$mode) } }

Notice that each receive_event method of the various classes has what amounts to a nested case statement inside it (hence the description "tests-in-methods"). These if statements are needed to work out which combination of argument types has actually been received, and what action to take as a result. Also note that the last alternative in each method is always the same: give up and pass the arguments to the parent class, in the hope that it will be able to handle them.

The various cases that are directly tested don't explicitly cover all possible combinations of argument types. To do so would require a total of 96 alternatives (4 window classes x 6 event types x 4 modes). Instead, the handlers rely on the inheritance relationships of the various classes. For example, there is no specific test to detect a ResizableWindow object receiving a MoveEvent in OffMode. If that actually ever happens, the following sequence ensues:

• ResizableWindow: :receive_event is called, and tests for the various cases it handles. None match, so it executes the else block, invoking its parent class's receive_event method on the same set of arguments.

• In response, MovableWindow: :receive_event is called, and tests for the various cases that it handles. Once again, none match, so the else block is selected and invokes the grandparental receive_event method on the same arguments.

• That means Window: :receive_event is called, and it too tests its various cases. The first case discovers that the MoveEvent argument can be treated as a Event

Multiple Dispatch via "Tests-in-Methods" 371



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.