in reply to Re: •Re: It's a dog, but what kind? (polymorphism , in Perl OO)
in thread It's a dog, but what kind? (polymorphism , in Perl OO)
Polymorphism is a much more general concept, and we skip over that generality by starting with the factory piece first.
See my reply below for why this isn't a good example of polymorphisim anyway. Update: blue_cowdawg's update fix the OP's polymorphisim issue.
I would be interested to see if the factory could be made without using eval, as well...I think it can, especially if the dogs were loaded previously in a more-safe matter.
It can using require $path_to_breed; instead of eval "use $breed;";. But it ammounts to almost the same thing, except that you have to specifiy the path to the breed file instead of the traditional 'module::name' format. As you say, it's also possible to load all the subclasses before anything is called, but that could get very inefficient fast.
My favored solution would be to map a breed via a hash:
my %breeds = ( cocker => 'dog::cocker', setter => 'dog::setter', ); sub new { my $class = shift; my $breed = shift; my $self = { }; if($breed) { my $breed_class = $breeds{$breed}; eval " use $breed_class "; die $@ if $@; $self = $breed_class->new(); } else { bless $self, $class; } return $self; }
----
: () { :|:& };:
Note: All code is untested, unless otherwise stated
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Re: •Re: It's a dog, but what kind? (polymorphism , in Perl OO)
by flyingmoose (Priest) on Mar 24, 2004 at 00:43 UTC | |
by hardburn (Abbot) on Mar 24, 2004 at 14:10 UTC |