in reply to Setting common object attributes
To expand a little on rjts post: If all your car objects basically act the same but have different attributes then you don't really need to subclass. You just need a simple way to apply default attributes when you build your cars. You could have a set of standard attributes based on the car type, something like:
# You could load the hash from a database table, or just call the data +base for # each car. I'm just hardcoding for this example: my %car_models = ( Corolla => { drive=>'fwd', body=>'hatch', engine_capacity=>1798 }, Tercel => { drive=>'fwd', ... } ); while (<DATA>) { chomp; my $car = Car->new(); my $model_attributes = $car_models{$_}; $car->drive_type($model_attributes->{drive}); $car->body_type($model_attributes->{body}); $car->engine_cap($model_attributes->{engine_capacity}); ... }
This way, you just look up the attributes based on the model and add them when you build your car. You could even have a 'load_defaults_for_model' function in your car class to automatically do the lookup when you create your car:
sub load_defaults_for_model { my $self=shift; my $model_attributes = $car_models{$self->{Model}}; $self->drive_type($model_attributes->{drive}); $self->body_type($model_attributes->{body}); $self->engine_cap($model_attributes->{engine_capacity}); } sub new { my ($class, $model) = @_; my $new_obj = { .... build your object .... }; bless $new_obj, $class; if (defined $model) { $new_obj->{model} = $model; $new_obj->load_defaults_for_model(); } return $new_obj; }
...roboticus
When your only tool is a hammer, all problems look like your thumb.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Setting common object attributes
by nevdka (Pilgrim) on Jul 18, 2013 at 06:05 UTC |