in reply to Creating Common Constructor

You could use a 'factory method' to keep track of the objects you create e.g
sub Zoo::factory { my($self, $class, $args) = @_; my $obj = "Zoo::Animal::$class"->new( $args ); $self->{"_${class}_count"}++; return $obj; } my $zoo = Zoo->new; my $camel = $zoo->factory("Camel");
That code isn't complete or tested but it should give you some idea of how to go about implementing a factory method.
HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: Creating Common Constructor
by themage (Friar) on Jul 13, 2003 at 12:44 UTC
    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;
      }
    }