in reply to Inheritance: parent class determine which child class to use?
You are looking something rather like the (appropriately, given the example) factory pattern. The "method" used to create an instance is the factory.
The following is based on Moritz' sample, cleaned up and tested: :-)
use strict; use warnings; package Car; my %carByType; sub new { my ($class, %opts) = @_; return bless \%opts, $class; } sub factory { my (%opts) = @_; die "Don't know how to make a new car" if !exists $opts{name} || !exists $carByType{$opts{name}}; $carByType{$opts{name}}->new(%opts); } sub describe { my ($self) = @_; my ($make) = ref ($self) =~ m/^Car::(.*)/; print "$make $self->{name}\n"; } sub REGISTER_TYPE { my ($type, $name) = @_; $carByType{$name} = $type; } package Car::BMW; our @ISA = qw/Car/; Car::BMW->REGISTER_TYPE('Z1'); Car::BMW->REGISTER_TYPE('Z3'); package main; my $z1 = Car::factory(name => 'Z1'); $z1->describe();
Prints:
BMW Z1
True laziness is hard work
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Inheritance: parent class determine which child class to use?
by fbicknel (Beadle) on Jul 31, 2012 at 14:05 UTC |
In Section
Seekers of Perl Wisdom