Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Re: Creating Common Constructor

by themage (Friar)
on Jul 13, 2003 at 12:44 UTC ( [id://273766]=note: print w/replies, xml ) Need Help??


in reply to Re: Creating Common Constructor
in thread Creating Common Constructor

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;
  }
}



Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://273766]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-23 20:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found