note
crashtest
<p>I see your code and I think [http://en.wikipedia.org/wiki/Decorator_pattern|Decorator pattern]. Basically, you create a class that wraps the original object, and dispatches all method calls to the original object, except for those you want to override/modify, or those that are new. The advantage here is if some other part of your code is referencing the object you are monkeying with, it won't suddenly find its behavior changed.</p>
<p>In Perl, you get the added bonus of being able to implement all the methods that just dispatch to the original object using <c>AUTOLOAD</c>. Below is an example I've used before, YMMV.
</p>
<p>
<code>
package MyDecorator;
sub new{
my ($class, $wrapped, %options) = @_;
my $self = {
wrapped => $wrapped,
options => \%options
};
bless $self, __PACKAGE__;
}
sub method1{
my $self = shift;
my $wrapped = $self->{'wrapped'}
# Do something different than what
# $wrapped->method1 would do.
# ...
}
sub method2{
my $self = shift;
my $wrapped = $self->{'wrapped'}
# method2 is a new method that now provides additional
# functionality for the object.
}
# Implement autoload to defer all the methods we can't handle to the
# wrapped class.
sub AUTOLOAD{
return if our $AUTOLOAD =~ /::DESTROY$/;
my $self = shift;
my ($method, @namespace) = reverse(split '::' => $AUTOLOAD);
my $wrapped = $self->{'wrapped'};
if ($wrapped->can($method)){
no strict 'refs';
$AUTOLOAD->($wrapped, @_);
}
else{
die "Cannot run or defer method \"$method\"!";
}
}
</code>
</p>
<p>(All this goes to show, once again, TIMTOWTDI. But also: I am no expert on object oriented design, so take this with a grain of salt.)</p>
701826
701826