in reply to Re: Creating Common Constructor
in thread Creating Common Constructor
sub Zoo::factory {
my ($self, $class, @args)=@_;
my $obj="Zoo::Animal::$class"->new(@args);
$self->{count}->{$class}++;
return $obj;
}
my $zoo=Zoo->new();
my $camel=$zoo->factory("Camel");
#Zoo.pm file
sub new {
...
$self->{animals}=[];
...
}
sub adquire {
my $self=shift;
push @{$self->{animals}}, @_;
}
sub count {
my $self=shift;
my %count=();
for my $anim (@{$self->{animals}}) {
$count{$anim->specie()}++;
}
return %count;
}
#Zoo/Animal.pm
...
sub specie {
return "unknow specie";
}
...
#Zoo/Animal/Camel.pm
...
sub specie {
return "cameloid Dromedarius"
}
# Main
my $zoo=Zoo->new();
$zoo->adquire(Zoo::Animal::Camel->new(), Zoo::Animal::Camel->new());
%count=$zoo->count();
sub adquire {
my $self=shift;
for my $anim (@_) {
$self->{count}->{$anim->specie()}++;
push @{$self->{animals}}, $anim;
}
}
|
|---|