in reply to Interfaces in Perl?
The import method will do nothing if you import the base class, but will die a horrible flaming death if you ever use or import a class that inherits from it which does not implement the abstract methods you want.package Foo; use Carp; # Time passes # Import method that checks existence of abstract methods in subclasse +s. sub import { my $pkg = shift; return if $pkg eq __PACKAGE__; foreach my $meth ( qw(foo bar) ) { $pkg->can($meth) or croak("Class $pkg does not define method $meth +"); } $pkg->SUPER::import(@_); }
Note that the base class cannot (with this method) define the abstract methods itself, it just lists them. (They could be in an array, etc.)
UPDATE
I added inheritance so one abstract class can inherit from
another. This breaks on multiple inheritance because Perl's
SUPER mechanism doesn't handle this cleanly.
UPDATE 2
tye pointed out in the chatter that I should document the
fact that if you define your own import method and don't
call the SUPER::import method inside of it, then you will
break this mechanism.
UPDATE 3
I took the snippet above and turned it into a useful
module which may be found at AbstractClass.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Abstract class methods
by Dominus (Parson) on Dec 01, 2000 at 04:40 UTC | |
by gregorovius (Friar) on Dec 01, 2000 at 06:15 UTC | |
by merlyn (Sage) on Dec 01, 2000 at 10:35 UTC | |
by tilly (Archbishop) on Dec 01, 2000 at 06:32 UTC | |
by tilly (Archbishop) on Dec 01, 2000 at 05:48 UTC | |
by Dominus (Parson) on Dec 01, 2000 at 06:01 UTC | |
Re (tilly) 1 (tests): Abstract class methods
by tilly (Archbishop) on Dec 01, 2000 at 06:00 UTC | |
Re: Abstract class methods
by merlyn (Sage) on Dec 01, 2000 at 04:27 UTC | |
by tilly (Archbishop) on Dec 01, 2000 at 04:34 UTC | |
Re: Abstract class methods
by Anonymous Monk on Feb 04, 2005 at 09:48 UTC |