in reply to Re: Abstract class methods
in thread Interfaces in Perl?
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:
And a class that "implements" DuckInterface: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;
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!"; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Re: Abstract class methods
by merlyn (Sage) on Dec 01, 2000 at 10:35 UTC | |
Re (tilly) 3 (same trick): Abstract class methods
by tilly (Archbishop) on Dec 01, 2000 at 06:32 UTC |