Mark's ( Dominus) solution in the other thread is just
what I was looking for. I want all classes where I
"use Interface;" to implement and not inherit the methods
listed in the Interface package. The particular design
problem I need this for is one in which I need each class,
regardless of what base class they inherit from, to
implement themselves a group of methods.
Java provides a built in facility for doing this, the
"implements" keyword, which works almost exactly as the
"use Abstract;" Mark proposes. (To it I would suggest adding
the word "Interface" to the abstract class name, to achieve
Java-like clarity through convention). Thus his example
would look like this:
package DuckInterface;
use Carp;
my @inheritors;
sub import {
my $caller = caller;
push @inheritors, $caller;
}
my @abstract_methods = qw(swim fly);
sub INIT {
my $bad = 0;
for my $class (@inheritors) {
for my $meth (@abstract_methods) {
no strict 'refs';
unless (defined &{"${class}::$meth"}) {
$bad=1;
warn "Class $class should implement DuckInterface, but does
+not define $meth.\n";
}
}
}
croak "Compilation aborted" if $bad;
}
1;
And a class that "implements" DuckInterface:
package RedDuck;
use DuckInterface;
sub swim {
"I swim like a red duck";
}
sub fly {
"I fly like a red duck, and DuckInterface guarantees I do!";
}
-
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.
|