I see your code and I think 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.
In Perl, you get the added bonus of being able to implement all the methods that just dispatch to the original object using AUTOLOAD. Below is an example I've used before, YMMV.
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\"!";
}
}
(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.)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.