I like this, but I would implement this with a small difference:
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");
I would implement this difference so I could use $zoo->{zbr} for something else, and would be easier to find the counts to every specie in the $Zoo, 'cause every key in the %{$zoo->{count}} would be a diferent specie.
The other way I think I could implement was without a factory method, but with a adquire method, with some changes:
#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();
If you prefer you could yet implement the count as an hash, and increment it in the adquire Zoo method, like this:
sub adquire {
my $self=shift;
for my $anim (@_) {
$self->{count}->{$anim->specie()}++;
push @{$self->{animals}}, $anim;
}
}
| [reply] |